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