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