Revert "vLAN . Support Policies."
[sdc/sdc-tosca.git] / src / main / java / org / openecomp / sdc / tosca / parser / impl / SdcCsarHelperImpl.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * sdc-distribution-client
4  * ================================================================================
5  * Copyright (C) 2017 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  * ============LICENSE_END=========================================================
19  */
20
21 package org.openecomp.sdc.tosca.parser.impl;
22
23 import java.util.*;
24 import java.util.Map.Entry;
25 import java.util.stream.Collectors;
26
27 import org.apache.commons.lang3.tuple.ImmutablePair;
28 import org.apache.commons.lang3.tuple.Pair;
29 import org.openecomp.sdc.tosca.parser.api.ISdcCsarHelper;
30 import org.openecomp.sdc.tosca.parser.config.ConfigurationManager;
31 import org.openecomp.sdc.toscaparser.api.CapabilityAssignments;
32 import org.openecomp.sdc.tosca.parser.utils.GeneralUtility;
33 import org.openecomp.sdc.toscaparser.api.RequirementAssignments;
34 import org.openecomp.sdc.tosca.parser.utils.SdcToscaUtility;
35 import org.openecomp.sdc.toscaparser.api.*;
36 import org.openecomp.sdc.toscaparser.api.elements.Metadata;
37 import org.openecomp.sdc.toscaparser.api.elements.NodeType;
38 import org.openecomp.sdc.toscaparser.api.functions.Function;
39 import org.openecomp.sdc.toscaparser.api.parameters.Input;
40 import org.slf4j.Logger;
41 import org.slf4j.LoggerFactory;
42
43 import static org.openecomp.sdc.tosca.parser.impl.SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID;
44
45 public class SdcCsarHelperImpl implements ISdcCsarHelper {
46
47     private static final String PATH_DELIMITER = "#";
48     private static final String CUSTOMIZATION_UUID = "customizationUUID";
49     private ToscaTemplate toscaTemplate;
50     private ConfigurationManager configurationManager;
51     private static Logger log = LoggerFactory.getLogger(SdcCsarHelperImpl.class.getName());
52
53     public SdcCsarHelperImpl(ToscaTemplate toscaTemplate) {
54         this.toscaTemplate = toscaTemplate;
55     }
56
57     public SdcCsarHelperImpl(ToscaTemplate toscaTemplate, ConfigurationManager configurationManager) {
58         this.toscaTemplate = toscaTemplate;
59         this.configurationManager = configurationManager;
60     }
61
62     @Override
63     //Sunny flow  - covered with UT, flat and nested
64     public String getNodeTemplatePropertyLeafValue(NodeTemplate nodeTemplate, String leafValuePath) {
65         if (nodeTemplate == null) {
66             log.error("getNodeTemplatePropertyLeafValue - nodeTemplate is null");
67             return null;
68         }
69         if (GeneralUtility.isEmptyString(leafValuePath)) {
70             log.error("getNodeTemplatePropertyLeafValue - leafValuePath is null or empty");
71             return null;
72         }
73         String[] split = getSplittedPath(leafValuePath);
74         LinkedHashMap<String, Property> properties = nodeTemplate.getProperties();
75         Object property = processProperties(split, properties);
76         return property == null || property instanceof Function ? null : String.valueOf(property);
77     }
78
79     @Override
80     public Object getNodeTemplatePropertyAsObject(NodeTemplate nodeTemplate, String leafValuePath) {
81         if (nodeTemplate == null) {
82             log.error("getNodeTemplatePropertyAsObject - nodeTemplate is null");
83             return null;
84         }
85         if (GeneralUtility.isEmptyString(leafValuePath)) {
86             log.error("getNodeTemplatePropertyAsObject - leafValuePath is null or empty");
87             return null;
88         }
89         String[] split = getSplittedPath(leafValuePath);
90         LinkedHashMap<String, Property> properties = nodeTemplate.getProperties();
91         return processProperties(split, properties);
92     }
93     
94     public Map<String, Map<String, Object>> getCpPropertiesFromVfcAsObject(NodeTemplate vfc) {
95         if (vfc == null) {
96             log.error("getCpPropertiesFromVfc - vfc is null");
97             return new HashMap<>();
98         }
99
100         String presetProperty = "_ip_requirements";
101         Map<String, Map<String, Object>> cps = new HashMap<>();
102
103         Map<String, Property> props = vfc.getProperties();
104         if (props != null) {
105             // find all port names by pre-set property (ip_requirements)
106             for (Map.Entry<String, Property> entry : props.entrySet()) {
107                 if (entry.getKey().endsWith(presetProperty)) {
108                     String portName = entry.getKey().replaceAll(presetProperty, "");
109                     cps.put(portName, new HashMap<>());
110                 }
111             }
112
113             if (cps.size() > 0) {
114                 // ports found - find all their properties
115                 for (String portName : cps.keySet()) {
116                     for (Map.Entry<String, Property> property: props.entrySet()) {
117                         if (property.getKey().startsWith(portName)) {
118                             String portProperty = property.getKey().replaceFirst(portName + "_", "");
119                             if (property.getValue() != null) {
120                                 cps.get(portName).put(portProperty, property.getValue().getValue());
121                             }
122                         }
123                     }
124                 }
125             }
126         }
127
128         return cps;
129     }
130
131     public Map<String, Map<String, Object>> getCpPropertiesFromVfc(NodeTemplate vfc) {
132
133         if (vfc == null) {
134             log.error("getCpPropertiesFromVfc - vfc is null");
135             return new HashMap<>();
136         }
137
138         String presetProperty = "_ip_requirements";
139         Map<String, Map<String, Object>> cps = new HashMap<>();
140
141         Map<String, Property> props = vfc.getProperties();
142         if (props != null) {
143             // find all port names by pre-set property (ip_requirements)
144             for (Map.Entry<String, Property> entry : props.entrySet()) {
145                 if (entry.getKey().endsWith(presetProperty)) {
146                     String portName = entry.getKey().replaceAll(presetProperty, "");
147                     cps.put(portName, new HashMap<>());
148                 }
149             }
150
151             if (cps.size() > 0) {
152                 // ports found - find all their properties
153                 for (String portName : cps.keySet()) {
154                     for (Map.Entry<String, Property> property: props.entrySet()) {
155                         if (property.getKey().startsWith(portName)) {
156                             Map<String, Object> portPaths = new HashMap<>();
157                             String portProperty = property.getKey().replaceFirst(portName + "_", "");
158                             buildPathMappedToValue(portProperty, property.getValue().getValue(), portPaths);
159
160                             cps.get(portName).putAll(portPaths);
161                         }
162                     }
163                 }
164             }
165         }
166
167         return cps;
168     }
169
170     @SuppressWarnings("unchecked")
171     private void buildPathMappedToValue(String path, Object property, Map<String, Object> pathsMap) {
172         if (property instanceof Map) {
173             for (Map.Entry<String, Object> item : ((Map<String, Object>) property).entrySet()) {
174                 if (item.getValue() instanceof Map || item.getValue() instanceof List) {
175                     buildPathMappedToValue(path + PATH_DELIMITER + item.getKey(), item.getValue(), pathsMap);
176                 } else {
177                     pathsMap.put(path + PATH_DELIMITER + item.getKey(), item.getValue());
178                 }
179             }
180         } else if (property instanceof List) {
181             for (Object item: (List<Object>)property) {
182                 buildPathMappedToValue(path, item, pathsMap);
183             }
184         } else {
185             pathsMap.put(path, property);
186         }
187
188     }
189
190     @Override
191     //Sunny flow - covered with UT
192     public List<NodeTemplate> getServiceVlList() {
193         List<NodeTemplate> serviceVlList = getNodeTemplateBySdcType(toscaTemplate.getTopologyTemplate(), SdcTypes.VL);
194         return serviceVlList;
195     }
196
197     @Override
198     //Sunny flow - covered with UT
199     public List<NodeTemplate> getServiceVfList() {
200         List<NodeTemplate> serviceVfList = getNodeTemplateBySdcType(toscaTemplate.getTopologyTemplate(), SdcTypes.VF);
201         return serviceVfList;
202     }
203
204     @Override
205     //Sunny flow - covered with UT
206     public String getMetadataPropertyValue(Metadata metadata, String metadataPropertyName) {
207         if (GeneralUtility.isEmptyString(metadataPropertyName)) {
208             log.error("getMetadataPropertyValue - the metadataPropertyName is null or empty");
209             return null;
210         }
211         if (metadata == null) {
212             log.error("getMetadataPropertyValue - the metadata is null");
213             return null;
214         }
215         String metadataPropertyValue = metadata.getValue(metadataPropertyName);
216         return metadataPropertyValue;
217     }
218
219
220     @Override
221     //Sunny flow - covered with UT
222     public List<NodeTemplate> getServiceNodeTemplatesByType(String nodeType) {
223         if (GeneralUtility.isEmptyString(nodeType)) {
224             log.error("getServiceNodeTemplatesByType - nodeType - is null or empty");
225             return new ArrayList<>();
226         }
227
228         List<NodeTemplate> res = new ArrayList<>();
229         List<NodeTemplate> nodeTemplates = toscaTemplate.getNodeTemplates();
230         for (NodeTemplate nodeTemplate : nodeTemplates) {
231             if (nodeType.equals(nodeTemplate.getTypeDefinition().getType())) {
232                 res.add(nodeTemplate);
233             }
234         }
235
236         return res;
237     }
238
239
240     @Override
241     public List<NodeTemplate> getServiceNodeTemplates() {
242         List<NodeTemplate> nodeTemplates = toscaTemplate.getNodeTemplates();
243         return nodeTemplates;
244     }
245
246     @Override
247     //Sunny flow - covered with UT
248     public List<NodeTemplate> getVfcListByVf(String vfCustomizationId) {
249         if (GeneralUtility.isEmptyString(vfCustomizationId)) {
250             log.error("getVfcListByVf - vfCustomizationId - is null or empty");
251             return new ArrayList<>();
252         }
253
254         List<NodeTemplate> serviceVfList = getServiceVfList();
255         NodeTemplate vfInstance = getNodeTemplateByCustomizationUuid(serviceVfList, vfCustomizationId);
256         List<NodeTemplate> vfcs = getNodeTemplateBySdcType(vfInstance, SdcTypes.VFC);
257         vfcs.addAll(getNodeTemplateBySdcType(vfInstance, SdcTypes.CVFC));
258
259         return vfcs;
260     }
261
262     @Override
263     //Sunny flow - covered with UT
264     public List<Group> getVfModulesByVf(String vfCustomizationUuid) {
265         List<NodeTemplate> serviceVfList = getServiceVfList();
266         NodeTemplate nodeTemplateByCustomizationUuid = getNodeTemplateByCustomizationUuid(serviceVfList, vfCustomizationUuid);
267         if (nodeTemplateByCustomizationUuid != null) {
268             /*SubstitutionMappings substitutionMappings = nodeTemplateByCustomizationUuid.getSubstitutionMappings();
269                         if (substitutionMappings != null){
270                                 List<Group> groups = substitutionMappings.getGroups();
271                                 if (groups != null){
272                                         List<Group> collect = groups.stream().filter(x -> "org.openecomp.groups.VfModule".equals(x.getTypeDefinition().getType())).collect(Collectors.toList());
273                                         log.debug("getVfModulesByVf - VfModules are {}", collect);
274                                         return collect;
275                                 }
276                         }*/
277             String name = nodeTemplateByCustomizationUuid.getName();
278             String normaliseComponentInstanceName = SdcToscaUtility.normaliseComponentInstanceName(name);
279             List<Group> serviceLevelGroups = toscaTemplate.getTopologyTemplate().getGroups();
280             log.debug("getVfModulesByVf - VF node template name {}, normalized name {}. Searching groups on service level starting with VF normalized name...", name, normaliseComponentInstanceName);
281             if (serviceLevelGroups != null) {
282                 List<Group> collect = serviceLevelGroups
283                         .stream()
284                         .filter(x -> "org.openecomp.groups.VfModule".equals(x.getTypeDefinition().getType()) && x.getName().startsWith(normaliseComponentInstanceName))
285                         .collect(Collectors.toList());
286                 return collect;
287             }
288         }
289         return new ArrayList<>();
290     }
291
292     @Override
293     //Sunny flow - covered with UT
294     public String getServiceInputLeafValueOfDefault(String inputLeafValuePath) {
295         if (GeneralUtility.isEmptyString(inputLeafValuePath)) {
296             log.error("getServiceInputLeafValueOfDefault - inputLeafValuePath is null or empty");
297             return null;
298         }
299
300         String[] split = getSplittedPath(inputLeafValuePath);
301         if (split.length < 2 || !split[1].equals("default")) {
302             log.error("getServiceInputLeafValue - inputLeafValuePath should be of format <input name>#default[optionally #<rest of path>] ");
303             return null;
304         }
305
306         List<Input> inputs = toscaTemplate.getInputs();
307         if (inputs != null) {
308             Optional<Input> findFirst = inputs.stream().filter(x -> x.getName().equals(split[0])).findFirst();
309             if (findFirst.isPresent()) {
310                 Input input = findFirst.get();
311                 Object current = input.getDefault();
312                 Object property = iterateProcessPath(2, current, split);
313                 return property == null || property instanceof Function? null : String.valueOf(property);
314             }
315         }
316         log.error("getServiceInputLeafValue - value not found");
317         return null;
318     }
319
320     @Override
321     public Object getServiceInputLeafValueOfDefaultAsObject(String inputLeafValuePath) {
322         if (GeneralUtility.isEmptyString(inputLeafValuePath)) {
323             log.error("getServiceInputLeafValueOfDefaultAsObject - inputLeafValuePath is null or empty");
324             return null;
325         }
326
327         String[] split = getSplittedPath(inputLeafValuePath);
328         if (split.length < 2 || !split[1].equals("default")) {
329             log.error("getServiceInputLeafValueOfDefaultAsObject - inputLeafValuePath should be of format <input name>#default[optionally #<rest of path>] ");
330             return null;
331         }
332
333         List<Input> inputs = toscaTemplate.getInputs();
334         if (inputs != null) {
335             Optional<Input> findFirst = inputs.stream().filter(x -> x.getName().equals(split[0])).findFirst();
336             if (findFirst.isPresent()) {
337                 Input input = findFirst.get();
338                 Object current = input.getDefault();
339                 return iterateProcessPath(2, current, split);
340             }
341         }
342         log.error("getServiceInputLeafValueOfDefaultAsObject - value not found");
343         return null;
344     }
345
346     @SuppressWarnings({ "unchecked", "rawtypes" })
347     private Object iterateProcessPath(Integer index, Object current, String[] split) {
348         if (current == null) {
349             log.error("iterateProcessPath - this input has no default");
350             return null;
351         }
352         if (split.length > index) {
353             for (int i = index; i < split.length; i++) {
354                 if (current instanceof Map) {
355                     current = ((Map<String, Object>) current).get(split[i]);
356                 } else if (current instanceof List) {
357                     current = ((List) current).get(0);
358                     i--;
359                 }
360                  else {
361                         log.error("iterateProcessPath - found an unexpected leaf where expected to find a complex type");
362                         return null;
363                 }
364             }
365         }
366         if (current != null) {
367             return current;
368         }
369         log.error("iterateProcessPath - Path not Found");
370         return null;
371     }
372
373     private String[] getSplittedPath(String inputLeafValuePath) {
374         return inputLeafValuePath.split(PATH_DELIMITER);
375     }
376
377
378     @Override
379     //Sunny flow - covered with UT
380     public String getServiceSubstitutionMappingsTypeName() {
381         SubstitutionMappings substitutionMappings = toscaTemplate.getTopologyTemplate().getSubstitutionMappings();
382         if (substitutionMappings == null) {
383             log.debug("getServiceSubstitutionMappingsTypeName - No Substitution Mappings defined");
384             return null;
385         }
386
387         NodeType nodeType = substitutionMappings.getNodeDefinition();
388         if (nodeType == null) {
389             log.debug("getServiceSubstitutionMappingsTypeName - No Substitution Mappings node defined");
390             return null;
391         }
392
393         return nodeType.getType();
394     }
395
396     @Override
397     //Sunny flow - covered with UT
398     public Metadata getServiceMetadata() {
399         return toscaTemplate.getMetaData();
400     }
401
402     @Override
403     //Sunny flow - covered with UT
404     public Map<String, Object> getServiceMetadataProperties() {
405         if (toscaTemplate.getMetaData() == null){
406             return null;
407         }
408         return new HashMap<>(toscaTemplate.getMetaData().getAllProperties());
409     }
410
411     @Override
412     public Map<String, String> getServiceMetadataAllProperties() {
413         if (toscaTemplate.getMetaData() == null){
414             return null;
415         }
416         return toscaTemplate.getMetaData().getAllProperties();
417     }
418
419     @Override
420     //Sunny flow - covered with UT
421     public List<Input> getServiceInputs() {
422         return toscaTemplate.getInputs();
423     }
424
425     @Override
426     //Sunny flow - covered with UT
427     public String getGroupPropertyLeafValue(Group group, String leafValuePath) {
428         if (group == null) {
429             log.error("getGroupPropertyLeafValue - group is null");
430             return null;
431         }
432
433         if (GeneralUtility.isEmptyString(leafValuePath)) {
434             log.error("getGroupPropertyLeafValue - leafValuePath is null or empty");
435             return null;
436         }
437
438         String[] split = getSplittedPath(leafValuePath);
439         LinkedHashMap<String, Property> properties = group.getProperties();
440         Object property = processProperties(split, properties);
441         return property == null || property instanceof Function? null : String.valueOf(property);
442     }
443
444     @Override
445     public Object getGroupPropertyAsObject(Group group, String leafValuePath) {
446         if (group == null) {
447             log.error("getGroupPropertyAsObject - group is null");
448             return null;
449         }
450
451         if (GeneralUtility.isEmptyString(leafValuePath)) {
452             log.error("getGroupPropertyAsObject - leafValuePath is null or empty");
453             return null;
454         }
455
456         String[] split = getSplittedPath(leafValuePath);
457         LinkedHashMap<String, Property> properties = group.getProperties();
458         return processProperties(split, properties);
459     }
460
461     @Override
462     //Sunny flow - covered with UT
463     public List<NodeTemplate> getCpListByVf(String vfCustomizationId) {
464         List<NodeTemplate> cpList = new ArrayList<>();
465         if (GeneralUtility.isEmptyString(vfCustomizationId)) {
466             log.error("getCpListByVf vfCustomizationId string is empty");
467             return cpList;
468         }
469
470         List<NodeTemplate> serviceVfList = getServiceVfList();
471         if (serviceVfList == null || serviceVfList.size() == 0) {
472             log.error("getCpListByVf Vfs not exist for vfCustomizationId {}", vfCustomizationId);
473             return cpList;
474         }
475         NodeTemplate vfInstance = getNodeTemplateByCustomizationUuid(serviceVfList, vfCustomizationId);
476         if (vfInstance == null) {
477             log.debug("getCpListByVf vf list is null");
478             return cpList;
479         }
480         cpList = getNodeTemplateBySdcType(vfInstance, SdcTypes.CP);
481         if (cpList == null || cpList.size() == 0)
482             log.debug("getCpListByVf cps not exist for vfCustomizationId {}", vfCustomizationId);
483         return cpList;
484     }
485
486     @Override
487     //Sunny flow - covered with UT
488     public List<NodeTemplate> getMembersOfVfModule(NodeTemplate vf, Group serviceLevelVfModule) {
489         if (vf == null) {
490             log.error("getMembersOfVfModule - vf is null");
491             return new ArrayList<>();
492         }
493
494         if (serviceLevelVfModule == null || serviceLevelVfModule.getMetadata() == null || serviceLevelVfModule.getMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_VFMODULEMODELINVARIANTUUID) == null) {
495             log.error("getMembersOfVfModule - vfModule or its metadata is null. Cannot match a VF group based on invariantUuid from missing metadata.");
496             return new ArrayList<>();
497         }
498
499
500         SubstitutionMappings substitutionMappings = vf.getSubMappingToscaTemplate();
501         if (substitutionMappings != null) {
502             List<Group> groups = substitutionMappings.getGroups();
503             if (groups != null) {
504                 Optional<Group> findFirst = groups
505                         .stream()
506                         .filter(x -> (x.getMetadata() != null && serviceLevelVfModule.getMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_VFMODULEMODELINVARIANTUUID).equals(x.getMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_VFMODULEMODELINVARIANTUUID)))).findFirst();
507                 if (findFirst.isPresent()) {
508                     List<String> members = findFirst.get().getMembers();
509                     if (members != null) {
510                         List<NodeTemplate> collect = substitutionMappings.getNodeTemplates().stream().filter(x -> members.contains(x.getName())).collect(Collectors.toList());
511                         return collect;
512                     }
513                 }
514             }
515         }
516         return new ArrayList<>();
517     }
518
519     @Override
520     //Sunny flow - covered with UT
521     @SuppressWarnings("unchecked")
522     public List<Pair<NodeTemplate, NodeTemplate>> getNodeTemplatePairsByReqName(
523             List<NodeTemplate> listOfReqNodeTemplates, List<NodeTemplate> listOfCapNodeTemplates, String reqName) {
524
525         if (listOfReqNodeTemplates == null) {
526             log.error("getNodeTemplatePairsByReqName - listOfReqNodeTemplates is null");
527             return new ArrayList<>();
528         }
529
530         if (listOfCapNodeTemplates == null) {
531             log.error("getNodeTemplatePairsByReqName - listOfCapNodeTemplates is null");
532             return new ArrayList<>();
533         }
534
535         if (GeneralUtility.isEmptyString(reqName)) {
536             log.error("getNodeTemplatePairsByReqName - reqName is null or empty");
537             return new ArrayList<>();
538         }
539
540         List<Pair<NodeTemplate, NodeTemplate>> pairsList = new ArrayList<>();
541
542         for (NodeTemplate reqNodeTemplate : listOfReqNodeTemplates) {
543             List<RequirementAssignment> requirements = reqNodeTemplate.getRequirements().getRequirementsByName(reqName).getAll();
544             for (RequirementAssignment reqEntry : requirements) {
545                 String node = reqEntry.getNodeTemplateName();
546                 if (node != null) {
547                     Optional<NodeTemplate> findFirst = listOfCapNodeTemplates.stream().filter(x -> x.getName().equals(node)).findFirst();
548                     if (findFirst.isPresent()) {
549                         pairsList.add(new ImmutablePair<NodeTemplate, NodeTemplate>(reqNodeTemplate, findFirst.get()));
550                     }
551                 }
552             }
553         }
554
555         return pairsList;
556     }
557
558     @Override
559     //Sunny flow - covered with UT
560     //TODO constant strings
561     public List<NodeTemplate> getAllottedResources() {
562         List<NodeTemplate> nodeTemplates = null;
563         nodeTemplates = toscaTemplate.getTopologyTemplate().getNodeTemplates();
564         if (nodeTemplates.isEmpty()) {
565             log.error("getAllottedResources nodeTemplates not exist");
566         }
567         nodeTemplates = nodeTemplates.stream().filter(
568                 x -> x.getMetaData() != null && x.getMetaData().getValue("category").equals("Allotted Resource"))
569                 .collect(Collectors.toList());
570         if (nodeTemplates.isEmpty()) {
571             log.debug("getAllottedResources -  allotted resources not exist");
572         } else {
573         }
574
575         return nodeTemplates;
576     }
577
578     @Override
579     //Sunny flow - covered with UT
580     public String getTypeOfNodeTemplate(NodeTemplate nodeTemplate) {
581         if (nodeTemplate == null) {
582
583             log.error("getTypeOfNodeTemplate nodeTemplate is null");
584             return null;
585         }
586         return nodeTemplate.getTypeDefinition().getType();
587     }
588
589     /**
590      * This methdd is returning the csarConformanceLevel for input CSAR
591      * When csarConformanceLevel is configured with failOnError as False in Error Configuration; it
592      * assigns the default value to csarConformanceLevel which is the max level provided in
593      * Configuration file
594      * @return csarConformanceLevel
595      */
596     @Override
597     public String getConformanceLevel() {
598       LinkedHashMap<String, Object> csarMeta = toscaTemplate.getMetaProperties("csar.meta");
599       if (csarMeta == null){
600         log.warn("No csar.meta file is found in CSAR - this file should hold the conformance level of the CSAR. This might be OK for older CSARs.");
601         if (configurationManager != null && !configurationManager.getErrorConfiguration()
602             .getErrorInfo("CONFORMANCE_LEVEL_ERROR").getFailOnError()){
603           String csarConLevel = configurationManager.getConfiguration().getConformanceLevel().getMaxVersion();
604           log.warn("csarConformanceLevel is not found in input csar; defaulting to max version {}" , csarConLevel);
605           return csarConLevel;
606         }
607         else {
608           log.warn("csarConformanceLevel is not found in input csar; returning null as no defaults defined in error configuration");
609           return null;
610         }
611       }
612
613       Object conformanceLevel = csarMeta.get("SDC-TOSCA-Definitions-Version");
614       if (conformanceLevel != null){
615         String confLevelStr = conformanceLevel.toString();
616         log.debug("CSAR conformance level is {}", confLevelStr);
617         return confLevelStr;
618       } else {
619         log.error("Invalid csar.meta file - no entry found for SDC-TOSCA-Definitions-Version key. This entry should hold the conformance level.");
620         return null;
621       }
622     }
623         
624         
625         @Override
626         public String getNodeTemplateCustomizationUuid(NodeTemplate nt) {
627                 String res = null;
628                 if (nt != null && nt.getMetaData() != null){
629                         res = nt.getMetaData().getValue(CUSTOMIZATION_UUID);
630                 } else {
631                         log.error("Node template or its metadata is null");
632                 }
633                 return res;
634         }
635
636     public List<NodeTemplate> getNodeTemplateBySdcType(NodeTemplate parentNodeTemplate, SdcTypes sdcType) {
637         return getNodeTemplateBySdcType(parentNodeTemplate, sdcType, false); 
638     }
639     
640     private List<NodeTemplate> getNodeTemplateBySdcType(NodeTemplate parentNodeTemplate, SdcTypes sdcType, boolean isVNF)  {
641         
642         if (parentNodeTemplate == null) {
643             log.error("getNodeTemplateBySdcType - nodeTemplate is null or empty");
644             return new ArrayList<>();
645         }
646
647         if (sdcType == null) {
648             log.error("getNodeTemplateBySdcType - sdcType is null or empty");
649             return new ArrayList<>();
650         }
651
652         SubstitutionMappings substitutionMappings = parentNodeTemplate.getSubMappingToscaTemplate();
653
654         if (substitutionMappings != null) {
655             List<NodeTemplate> nodeTemplates = substitutionMappings.getNodeTemplates();
656             if (nodeTemplates != null && nodeTemplates.size() > 0) {
657                 if (sdcType.equals(SdcTypes.VFC) && isVNF)  {
658                         return nodeTemplates.stream()
659                                 .filter(x -> (x.getMetaData() != null &&
660                                         sdcType.getValue().equals(x.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_TYPE))) &&  isVNFType(x))
661                                 .collect(Collectors.toList());
662                 }
663                 else {
664                     return nodeTemplates.stream()
665                                 .filter(x -> (x.getMetaData() != null &&
666                                         sdcType.getValue().equals(x.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_TYPE))) &&  !isVNFType(x))
667                                 .collect(Collectors.toList());
668                 }
669             }
670             else {
671                 log.debug("getNodeTemplateBySdcType - SubstitutionMappings' node Templates not exist");
672             }
673         } else
674             log.debug("getNodeTemplateBySdcType - SubstitutionMappings not exist");
675
676         return new ArrayList<>();
677     }
678
679     public Map<String, String> filterNodeTemplatePropertiesByValue(NodeTemplate nodeTemplate, FilterType filterType, String pattern) {
680         Map<String, String> filterMap = new HashMap<>();
681
682         if (nodeTemplate == null) {
683             log.error("filterNodeTemplatePropertiesByValue nodeTemplate is null");
684             return filterMap;
685         }
686
687         if (filterType == null) {
688             log.error("filterNodeTemplatePropertiesByValue filterType is null");
689             return filterMap;
690         }
691
692         if (GeneralUtility.isEmptyString(pattern)) {
693             log.error("filterNodeTemplatePropertiesByValue pattern string is empty");
694             return filterMap;
695         }
696
697         Map<String, Property> ntProperties = nodeTemplate.getProperties();
698
699         if (ntProperties != null && ntProperties.size() > 0) {
700
701             for (Property current : ntProperties.values()) {
702                 filterProperties(current.getValue(), current.getName(), filterType, pattern, filterMap);
703             }
704         }
705
706         log.trace("filterNodeTemplatePropertiesByValue - filterMap value: {}", filterMap);
707
708         return filterMap;
709     }
710     
711         public NodeTemplate getVnfConfig(String vfCustomizationUuid) {
712                 
713                 if (GeneralUtility.isEmptyString(vfCustomizationUuid)) {
714             log.error("getVnfConfig - vfCustomizationId - is null or empty");
715             return null;
716         }
717
718         List<NodeTemplate> serviceVfList = getServiceVfList();
719         NodeTemplate vfInstance = getNodeTemplateByCustomizationUuid(serviceVfList, vfCustomizationUuid);
720         NodeTemplate vnfConfig = getNodeTemplateBySdcType(vfInstance, SdcTypes.VFC, true).stream().findAny().orElse(null);
721                 return vnfConfig;
722         }
723
724     @Override
725     public boolean hasTopology(NodeTemplate nodeTemplate) {
726         if (nodeTemplate == null) {
727             log.error("hasTopology - nodeTemplate - is null");
728             return false;
729         }
730
731         if (nodeTemplate.getMetaData() != null) {
732             String type = nodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_TYPE);
733             log.debug("hasTopology - node template {} is a {} type", nodeTemplate.getName(), type);
734             return SdcTypes.isComplex(type);
735         }
736
737         return false;
738     }
739
740     @Override
741     public List<NodeTemplate> getNodeTemplateChildren(NodeTemplate nodeTemplate) {
742         if (nodeTemplate == null) {
743             log.error("getNodeTemplateChildren - nodeTemplate - is null");
744             return new ArrayList<>();
745         }
746
747         SubstitutionMappings substitutionMappings = nodeTemplate.getSubMappingToscaTemplate();
748         if (substitutionMappings != null) {
749             List<NodeTemplate> nodeTemplates = substitutionMappings.getNodeTemplates();
750             if (nodeTemplates != null && nodeTemplates.size() > 0) {
751
752                 return nodeTemplates.stream()
753                         .filter(x -> !isVNFType(x))
754                         .collect(Collectors.toList());
755             }
756             else {
757                 log.debug("getNodeTemplateChildren - SubstitutionMappings' node Templates not exist");
758             }
759         } else
760             log.debug("getNodeTemplateChildren - SubstitutionMappings not exist");
761
762         return new ArrayList<>();
763     }
764
765     @Override
766     public NodeTemplate getServiceNodeTemplateByNodeName(String nodeName) {
767         if (GeneralUtility.isEmptyString(nodeName)) {
768             log.error("getServiceNodeTemplateByNodeName - nodeName - is null or empty");
769             return null;
770         }
771
772         List<NodeTemplate> nodeTemplates = getServiceNodeTemplates();
773         Optional<NodeTemplate> findFirst =  nodeTemplates.stream().filter(nt -> nt.getName().equals(nodeName)).findFirst();
774
775         return findFirst.isPresent() ? findFirst.get() : null;
776     }
777
778     @Override
779     public Metadata getNodeTemplateMetadata(NodeTemplate nt) {
780         if (nt == null) {
781             log.error("getNodeTemplateMetadata - nt (node template) - is null");
782             return null;
783         }
784
785         return nt.getMetaData();
786     }
787
788     @Override
789     public CapabilityAssignments getCapabilitiesOf(NodeTemplate nt) {
790         if (nt == null) {
791             log.error("getCapabilitiesOf - nt (node template) - is null");
792             return null;
793         }
794
795         return nt.getCapabilities();
796     }
797
798     @Override
799     public RequirementAssignments getRequirementsOf(NodeTemplate nt) {
800         if (nt == null) {
801             log.error("getRequirementsOf - nt (node template) - is null");
802             return null;
803         }
804
805         return nt.getRequirements();
806     }
807
808     @Override
809     public String getCapabilityPropertyLeafValue(CapabilityAssignment capability, String pathToPropertyLeafValue) {
810         if (capability == null) {
811             log.error("getCapabilityPropertyLeafValue - capability is null");
812             return null;
813         }
814
815         if (GeneralUtility.isEmptyString(pathToPropertyLeafValue)) {
816             log.error("getCapabilityPropertyLeafValue - pathToPropertyLeafValue is null or empty");
817             return null;
818         }
819
820         String[] split = getSplittedPath(pathToPropertyLeafValue);
821         LinkedHashMap<String, Property> properties = capability.getProperties();
822         Object property = processProperties(split, properties);
823         return property == null || property instanceof Function ? null : String.valueOf(property);
824     }
825
826     /************************************* helper functions ***********************************/
827     private boolean isVNFType(NodeTemplate nt) {
828         return nt.getType().endsWith("VnfConfiguration");
829     }
830
831     @SuppressWarnings("unchecked")
832     private Map<String, String> filterProperties(Object property, String path, FilterType filterType, String pattern, Map<String, String> filterMap) {
833
834         if (property instanceof Map) {
835             for (Map.Entry<String, Object> item: ((Map<String, Object>) property).entrySet()) {
836                 String itemPath = path + PATH_DELIMITER + item.getKey();
837                 filterProperties(item.getValue(), itemPath, filterType, pattern, filterMap);
838             }
839         } else if (property instanceof List) {
840             for (Object item: (List<Object>)property) {
841                 filterProperties(item, path, filterType, pattern, filterMap);
842             }
843         } else {
844             if (filterType.isMatch(property.toString(), pattern)) {
845                 filterMap.put(path, property.toString());
846             }
847         }
848
849         return filterMap;
850     }
851
852     public List<NodeTemplate> getServiceNodeTemplateBySdcType(SdcTypes sdcType) {
853         if (sdcType == null) {
854             log.error("getServiceNodeTemplateBySdcType - sdcType is null or empty");
855             return new ArrayList<>();
856         }
857
858         TopologyTemplate topologyTemplate = toscaTemplate.getTopologyTemplate();
859         return getNodeTemplateBySdcType(topologyTemplate, sdcType);
860     }
861  
862
863     /************************************* helper functions ***********************************/
864     private List<NodeTemplate> getNodeTemplateBySdcType(TopologyTemplate topologyTemplate, SdcTypes sdcType) {
865         if (sdcType == null) {
866             log.error("getNodeTemplateBySdcType - sdcType is null or empty");
867             return new ArrayList<>();
868         }
869
870         if (topologyTemplate == null) {
871             log.error("getNodeTemplateBySdcType - topologyTemplate is null");
872             return new ArrayList<>();
873         }
874
875         List<NodeTemplate> nodeTemplates = topologyTemplate.getNodeTemplates();
876
877         if (nodeTemplates != null && nodeTemplates.size() > 0)
878             return nodeTemplates.stream().filter(x -> (x.getMetaData() != null && sdcType.getValue().equals(x.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_TYPE)))).collect(Collectors.toList());
879
880         log.debug("getNodeTemplateBySdcType - topologyTemplate's nodeTemplates not exist");
881         return new ArrayList<>();
882     }
883
884     //Assumed to be unique property for the list
885     private NodeTemplate getNodeTemplateByCustomizationUuid(List<NodeTemplate> nodeTemplates, String customizationId) {
886        if (customizationId != null) {
887             Optional<NodeTemplate> findFirst = nodeTemplates.stream().filter(x -> (x.getMetaData() != null && customizationId.equals(x.getMetaData().getValue(PROPERTY_NAME_CUSTOMIZATIONUUID)))).findFirst();
888             return findFirst.isPresent() ? findFirst.get() : null;
889         }
890         else {
891             log.error("getNodeTemplateByCustomizationUuid - customizationId is null");
892             return null;
893         }
894     }
895
896     private Object processProperties(String[] split, LinkedHashMap<String, Property> properties) {
897         Optional<Entry<String, Property>> findFirst = properties.entrySet().stream().filter(x -> x.getKey().equals(split[0])).findFirst();
898         if (findFirst.isPresent()) {
899             Property property = findFirst.get().getValue();
900             Object current = property.getValue();
901             return iterateProcessPath(1, current, split);
902         }
903         String propName = (split != null && split.length > 0 ? split[0] : null);
904         log.error("processProperties - property {} not found", propName);
905         return null;
906     }
907
908         
909
910     
911     
912 }