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
11 * http://www.apache.org/licenses/LICENSE-2.0
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=========================================================
21 package org.onap.sdc.tosca.parser.impl;
23 import static java.util.stream.Collectors.toList;
25 import java.util.ArrayList;
26 import java.util.Arrays;
27 import java.util.Collections;
28 import java.util.HashMap;
29 import java.util.HashSet;
30 import java.util.LinkedHashMap;
31 import java.util.List;
33 import java.util.Map.Entry;
34 import java.util.Optional;
35 import java.util.stream.Collectors;
37 import org.apache.commons.lang3.StringUtils;
38 import org.apache.commons.lang3.tuple.ImmutablePair;
39 import org.apache.commons.lang3.tuple.Pair;
40 import org.onap.sdc.tosca.parser.api.IEntityDetails;
41 import org.onap.sdc.tosca.parser.api.ISdcCsarHelper;
42 import org.onap.sdc.tosca.parser.config.ConfigurationManager;
43 import org.onap.sdc.tosca.parser.elements.queries.EntityQuery;
44 import org.onap.sdc.tosca.parser.elements.queries.TopologyTemplateQuery;
45 import org.onap.sdc.tosca.parser.enums.FilterType;
46 import org.onap.sdc.tosca.parser.enums.PropertySchemaType;
47 import org.onap.sdc.tosca.parser.enums.SdcTypes;
48 import org.onap.sdc.tosca.parser.utils.GeneralUtility;
49 import org.onap.sdc.tosca.parser.utils.PropertyUtils;
50 import org.onap.sdc.tosca.parser.utils.SdcToscaUtility;
51 import org.onap.sdc.toscaparser.api.CapabilityAssignment;
52 import org.onap.sdc.toscaparser.api.CapabilityAssignments;
53 import org.onap.sdc.toscaparser.api.Group;
54 import org.onap.sdc.toscaparser.api.NodeTemplate;
55 import org.onap.sdc.toscaparser.api.Policy;
56 import org.onap.sdc.toscaparser.api.Property;
57 import org.onap.sdc.toscaparser.api.RequirementAssignment;
58 import org.onap.sdc.toscaparser.api.RequirementAssignments;
59 import org.onap.sdc.toscaparser.api.SubstitutionMappings;
60 import org.onap.sdc.toscaparser.api.TopologyTemplate;
61 import org.onap.sdc.toscaparser.api.ToscaTemplate;
62 import org.onap.sdc.toscaparser.api.elements.DataType;
63 import org.onap.sdc.toscaparser.api.elements.InterfacesDef;
64 import org.onap.sdc.toscaparser.api.elements.Metadata;
65 import org.onap.sdc.toscaparser.api.elements.NodeType;
66 import org.onap.sdc.toscaparser.api.functions.Function;
67 import org.onap.sdc.toscaparser.api.parameters.Input;
68 import org.slf4j.Logger;
69 import org.slf4j.LoggerFactory;
71 public class SdcCsarHelperImpl implements ISdcCsarHelper {
73 private static final String PATH_DELIMITER = "#";
74 private static final String CUSTOMIZATION_UUID = "customizationUUID";
75 private ToscaTemplate toscaTemplate;
76 private ConfigurationManager configurationManager;
77 private static Logger log = LoggerFactory.getLogger(SdcCsarHelperImpl.class.getName());
79 public SdcCsarHelperImpl(ToscaTemplate toscaTemplate) {
80 this.toscaTemplate = toscaTemplate;
83 public SdcCsarHelperImpl(ToscaTemplate toscaTemplate, ConfigurationManager configurationManager) {
84 this.toscaTemplate = toscaTemplate;
85 this.configurationManager = configurationManager;
89 public List<Policy> getPoliciesOfTarget(NodeTemplate nodeTemplate) {
90 return getPoliciesOfNodeTemplate(nodeTemplate.getName())
92 .sorted(Policy::compareTo)
97 public List<Policy> getPoliciesOfOriginOfNodeTemplate(NodeTemplate nodeTemplate) {
98 if(StringUtils.isNotEmpty(nodeTemplate.getName())){
99 return getNodeTemplateByName(nodeTemplate.getName()).getOriginComponentTemplate().getPolicies();
101 return new ArrayList<>();
105 public List<Policy> getPoliciesOfTargetByToscaPolicyType(NodeTemplate nodeTemplate, String policyTypeName) {
106 return getPoliciesOfNodeTemplate(nodeTemplate.getName())
108 .filter(p->p.getType().equals(policyTypeName))
109 .sorted(Policy::compareTo)
114 public List<Policy> getPoliciesOfOriginOfNodeTemplateByToscaPolicyType(NodeTemplate nodeTemplate, String policyTypeName) {
115 return getPoliciesOfOriginOfNodeTemplate(nodeTemplate)
117 .filter(p->p.getType().equals(policyTypeName))
118 .sorted(Policy::compareTo)
123 public List<NodeTemplate> getPolicyTargetsFromTopologyTemplate(String policyName) {
124 if(toscaTemplate.getNodeTemplates() == null){
125 return new ArrayList<>();
127 List<String> targetNames = getPolicyTargets(policyName);
128 return toscaTemplate.getNodeTemplates().stream()
129 .filter(nt->targetNames.contains(nt.getName()))
134 public List<NodeTemplate> getPolicyTargetsFromOrigin(NodeTemplate nodeTemplate, String policyName) {
135 if(StringUtils.isNotEmpty(nodeTemplate.getName())){
136 Optional<Policy> policyOpt = getNodeTemplateByName(nodeTemplate.getName())
137 .getOriginComponentTemplate()
140 .filter(p -> p.getName()
143 if(policyOpt.isPresent()){
144 List<String> targets = policyOpt.get().getTargets();
145 if (targets != null) {
146 return nodeTemplate.getOriginComponentTemplate().getNodeTemplates()
148 .filter(nt -> targets.contains(nt.getName())).collect(Collectors.toList());
152 return new ArrayList<>();
156 public List<Policy> getPoliciesOfTopologyTemplate(){
157 if(toscaTemplate.getPolicies() == null)
158 return new ArrayList<>();
159 return toscaTemplate.getPolicies()
161 .sorted(Policy::compareTo)
166 public List<Policy> getPoliciesOfTopologyTemplateByToscaPolicyType(String policyTypeName){
167 if(toscaTemplate.getPolicies() == null)
168 return new ArrayList<>();
169 return toscaTemplate.getPolicies()
171 .filter(p->p.getType().equals(policyTypeName))
172 .sorted(Policy::compareTo)
176 public NodeTemplate getNodeTemplateByName(String nodeTemplateName) {
177 if(toscaTemplate.getNodeTemplates() == null)
179 return toscaTemplate.getNodeTemplates()
181 .filter(nt -> nt.getName().equals(nodeTemplateName))
182 .findFirst().orElse(null);
185 private List<Policy> getPoliciesOfNodeTemplate(String nodeTemplateName) {
186 if(toscaTemplate.getPolicies() == null)
187 return new ArrayList<>();
188 return toscaTemplate.getPolicies()
190 .filter(p -> p.getTargets()!= null && p.getTargets().contains(nodeTemplateName))
194 private List<String> getPolicyTargets(String policyName) {
195 return getPolicyByName(policyName).map(Policy::getTargets).orElse(new ArrayList<>());
198 private List<String> getGroupMembers(String groupName) {
199 return getGroupByName(groupName).map(Group::getMembers).orElse(new ArrayList<>());
202 private Optional<Policy> getPolicyByName(String policyName) {
203 if(toscaTemplate.getPolicies() == null)
204 return Optional.empty();
205 return toscaTemplate.getPolicies()
207 .filter(p -> p.getName().equals(policyName)).findFirst();
210 private Optional<Group> getGroupByName(String groupName) {
211 if(toscaTemplate.getGroups() == null)
212 return Optional.empty();
213 return toscaTemplate.getGroups()
215 .filter(g -> g.getName().equals(groupName)).findFirst();
219 //Sunny flow - covered with UT, flat and nested
220 public String getNodeTemplatePropertyLeafValue(NodeTemplate nodeTemplate, String leafValuePath) {
221 Object value = getNodeTemplatePropertyValueAsObject(nodeTemplate, leafValuePath);
222 return value == null || value instanceof Function ? null : String.valueOf(value);
226 public Object getNodeTemplatePropertyValueAsObject(NodeTemplate nodeTemplate, String leafValuePath) {
227 if (nodeTemplate == null) {
228 log.error("getNodeTemplatePropertyValueAsObject - nodeTemplate is null");
231 if (GeneralUtility.isEmptyString(leafValuePath)) {
232 log.error("getNodeTemplatePropertyValueAsObject - leafValuePath is null or empty");
235 String[] split = getSplittedPath(leafValuePath);
236 LinkedHashMap<String, Property> properties = nodeTemplate.getProperties();
237 return PropertyUtils.processProperties(split, properties);
240 public Map<String, Map<String, Object>> getCpPropertiesFromVfcAsObject(NodeTemplate vfc) {
242 log.error("getCpPropertiesFromVfc - vfc is null");
243 return new HashMap<>();
246 String presetProperty = "_ip_requirements";
247 Map<String, Map<String, Object>> cps = new HashMap<>();
249 Map<String, Property> props = vfc.getProperties();
251 // find all port names by pre-set property (ip_requirements)
252 for (Map.Entry<String, Property> entry : props.entrySet()) {
253 if (entry.getKey().endsWith(presetProperty)) {
254 String portName = entry.getKey().replaceAll(presetProperty, "");
255 cps.put(portName, new HashMap<>());
259 findPutAllPortsProperties(cps, props);
265 private void findPutAllPortsProperties(Map<String, Map<String, Object>> cps, Map<String, Property> props) {
266 if (!cps.isEmpty()) {
267 for (Entry<String, Map<String, Object>> port : cps.entrySet()) {
268 for (Map.Entry<String, Property> property: props.entrySet()) {
269 if (property.getKey().startsWith(port.getKey())) {
270 String portProperty = property.getKey().replaceFirst(port.getKey() + "_", "");
271 if (property.getValue() != null) {
272 cps.get(port.getKey()).put(portProperty, property.getValue().getValue());
280 public Map<String, Map<String, Object>> getCpPropertiesFromVfc(NodeTemplate vfc) {
283 log.error("getCpPropertiesFromVfc - vfc is null");
284 return new HashMap<>();
287 String presetProperty = "_ip_requirements";
288 Map<String, Map<String, Object>> cps = new HashMap<>();
290 Map<String, Property> props = vfc.getProperties();
292 // find all port names by pre-set property (ip_requirements)
293 for (Map.Entry<String, Property> entry : props.entrySet()) {
294 if (entry.getKey().endsWith(presetProperty)) {
295 String portName = entry.getKey().replaceAll(presetProperty, "");
296 cps.put(portName, new HashMap<>());
299 findBuildPutAllPortsProperties(cps, props);
305 private void findBuildPutAllPortsProperties(Map<String, Map<String, Object>> cps, Map<String, Property> props) {
306 if (!cps.isEmpty()) {
307 for (Entry<String, Map<String, Object>> port : cps.entrySet()) {
308 for (Map.Entry<String, Property> property: props.entrySet()) {
309 if (property.getKey().startsWith(port.getKey())) {
310 Map<String, Object> portPaths = new HashMap<>();
311 String portProperty = property.getKey().replaceFirst(port.getKey() + "_", "");
312 buildPathMappedToValue(portProperty, property.getValue().getValue(), portPaths);
313 cps.get(port.getKey()).putAll(portPaths);
320 @SuppressWarnings("unchecked")
321 private void buildPathMappedToValue(String path, Object property, Map<String, Object> pathsMap) {
322 if (property instanceof Map) {
323 for (Map.Entry<String, Object> item : ((Map<String, Object>) property).entrySet()) {
324 if (item.getValue() instanceof Map || item.getValue() instanceof List) {
325 buildPathMappedToValue(path + PATH_DELIMITER + item.getKey(), item.getValue(), pathsMap);
327 pathsMap.put(path + PATH_DELIMITER + item.getKey(), item.getValue());
330 } else if (property instanceof List) {
331 for (Object item: (List<Object>)property) {
332 buildPathMappedToValue(path, item, pathsMap);
335 pathsMap.put(path, property);
341 //Sunny flow - covered with UT
342 public List<NodeTemplate> getServiceVlList() {
343 return getNodeTemplateBySdcType(toscaTemplate.getTopologyTemplate(), SdcTypes.VL);
347 //Sunny flow - covered with UT
348 public List<NodeTemplate> getServiceVfList() {
349 return getNodeTemplateBySdcType(toscaTemplate.getTopologyTemplate(), SdcTypes.VF);
353 //Sunny flow - covered with UT
354 public String getMetadataPropertyValue(Metadata metadata, String metadataPropertyName) {
355 if (GeneralUtility.isEmptyString(metadataPropertyName)) {
356 log.error("getMetadataPropertyValue - the metadataPropertyName is null or empty");
359 if (metadata == null) {
360 log.error("getMetadataPropertyValue - the metadata is null");
363 return metadata.getValue(metadataPropertyName);
368 //Sunny flow - covered with UT
369 public List<NodeTemplate> getServiceNodeTemplatesByType(String nodeType) {
370 if (GeneralUtility.isEmptyString(nodeType)) {
371 log.error("getServiceNodeTemplatesByType - nodeType - is null or empty");
372 return new ArrayList<>();
375 List<NodeTemplate> res = new ArrayList<>();
376 List<NodeTemplate> nodeTemplates = toscaTemplate.getNodeTemplates();
377 for (NodeTemplate nodeTemplate : nodeTemplates) {
378 if (nodeType.equals(nodeTemplate.getTypeDefinition().getType())) {
379 res.add(nodeTemplate);
388 public List<NodeTemplate> getServiceNodeTemplates() {
389 return toscaTemplate.getNodeTemplates();
393 //Sunny flow - covered with UT
394 public List<NodeTemplate> getVfcListByVf(String vfCustomizationId) {
395 if (GeneralUtility.isEmptyString(vfCustomizationId)) {
396 log.error("getVfcListByVf - vfCustomizationId - is null or empty");
397 return new ArrayList<>();
400 List<NodeTemplate> serviceVfList = getServiceVfList();
401 NodeTemplate vfInstance = getNodeTemplateByCustomizationUuid(serviceVfList, vfCustomizationId);
402 List<NodeTemplate> vfcs = getNodeTemplateBySdcType(vfInstance, SdcTypes.VFC);
403 vfcs.addAll(getNodeTemplateBySdcType(vfInstance, SdcTypes.CVFC));
409 //Sunny flow - covered with UT
410 public List<Group> getVfModulesByVf(String vfCustomizationUuid) {
411 List<NodeTemplate> serviceVfList = getServiceVfList();
412 NodeTemplate nodeTemplateByCustomizationUuid = getNodeTemplateByCustomizationUuid(serviceVfList, vfCustomizationUuid);
413 if (nodeTemplateByCustomizationUuid != null) {
414 String name = nodeTemplateByCustomizationUuid.getName();
415 String normaliseComponentInstanceName = SdcToscaUtility.normaliseComponentInstanceName(name);
416 List<Group> serviceLevelGroups = toscaTemplate.getTopologyTemplate().getGroups();
417 log.debug("getVfModulesByVf - VF node template name {}, normalized name {}. Searching groups on service level starting with VF normalized name...", name, normaliseComponentInstanceName);
418 if (serviceLevelGroups != null) {
419 return serviceLevelGroups
421 .filter(x -> "org.openecomp.groups.VfModule".equals(x.getTypeDefinition().getType()) && x.getName().startsWith(normaliseComponentInstanceName))
425 return new ArrayList<>();
429 //Sunny flow - covered with UT
430 public String getServiceInputLeafValueOfDefault(String inputLeafValuePath) {
431 if (GeneralUtility.isEmptyString(inputLeafValuePath)) {
432 log.error("getServiceInputLeafValueOfDefault - inputLeafValuePath is null or empty");
436 String[] split = getSplittedPath(inputLeafValuePath);
437 if (split.length < 2 || !split[1].equals("default")) {
438 log.error("getServiceInputLeafValue - inputLeafValuePath should be of format <input name>#default[optionally #<rest of path>] ");
442 List<Input> inputs = toscaTemplate.getInputs();
443 if (inputs != null) {
444 Optional<Input> findFirst = inputs.stream().filter(x -> x.getName().equals(split[0])).findFirst();
445 if (findFirst.isPresent()) {
446 Input input = findFirst.get();
447 Object current = input.getDefault();
448 Object property = PropertyUtils.iterateProcessPath(2, current, split);
449 return property == null || property instanceof Function? null : String.valueOf(property);
452 log.error("getServiceInputLeafValue - value not found");
457 public Object getServiceInputLeafValueOfDefaultAsObject(String inputLeafValuePath) {
458 if (GeneralUtility.isEmptyString(inputLeafValuePath)) {
459 log.error("getServiceInputLeafValueOfDefaultAsObject - inputLeafValuePath is null or empty");
463 String[] split = getSplittedPath(inputLeafValuePath);
464 if (split.length < 2 || !split[1].equals("default")) {
465 log.error("getServiceInputLeafValueOfDefaultAsObject - inputLeafValuePath should be of format <input name>#default[optionally #<rest of path>] ");
469 List<Input> inputs = toscaTemplate.getInputs();
470 if (inputs != null) {
471 Optional<Input> findFirst = inputs.stream().filter(x -> x.getName().equals(split[0])).findFirst();
472 if (findFirst.isPresent()) {
473 Input input = findFirst.get();
474 Object current = input.getDefault();
475 return PropertyUtils.iterateProcessPath(2, current, split);
478 log.error("getServiceInputLeafValueOfDefaultAsObject - value not found");
482 private String[] getSplittedPath(String leafValuePath) {
483 return leafValuePath.split(PATH_DELIMITER);
488 //Sunny flow - covered with UT
489 public String getServiceSubstitutionMappingsTypeName() {
490 SubstitutionMappings substitutionMappings = toscaTemplate.getTopologyTemplate().getSubstitutionMappings();
491 if (substitutionMappings == null) {
492 log.debug("getServiceSubstitutionMappingsTypeName - No Substitution Mappings defined");
496 NodeType nodeType = substitutionMappings.getNodeDefinition();
497 if (nodeType == null) {
498 log.debug("getServiceSubstitutionMappingsTypeName - No Substitution Mappings node defined");
502 return nodeType.getType();
506 //Sunny flow - covered with UT
507 public Metadata getServiceMetadata() {
508 return toscaTemplate.getMetaData();
512 //Sunny flow - covered with UT
513 public Map<String, Object> getServiceMetadataProperties() {
514 if (toscaTemplate.getMetaData() == null){
517 return new HashMap<>(toscaTemplate.getMetaData().getAllProperties());
521 public Map<String, String> getServiceMetadataAllProperties() {
522 if (toscaTemplate.getMetaData() == null){
525 return toscaTemplate.getMetaData().getAllProperties();
529 //Sunny flow - covered with UT
530 public List<Input> getServiceInputs() {
531 return toscaTemplate.getInputs();
535 //Sunny flow - covered with UT
536 public String getGroupPropertyLeafValue(Group group, String leafValuePath) {
538 log.error("getGroupPropertyLeafValue - group is null");
542 if (GeneralUtility.isEmptyString(leafValuePath)) {
543 log.error("getGroupPropertyLeafValue - leafValuePath is null or empty");
547 String[] split = getSplittedPath(leafValuePath);
548 LinkedHashMap<String, Property> properties = group.getProperties();
549 Object property = PropertyUtils.processProperties(split, properties);
550 return property == null || property instanceof Function? null : String.valueOf(property);
554 public Object getGroupPropertyAsObject(Group group, String leafValuePath) {
556 log.error("getGroupPropertyAsObject - group is null");
560 if (GeneralUtility.isEmptyString(leafValuePath)) {
561 log.error("getGroupPropertyAsObject - leafValuePath is null or empty");
565 String[] split = getSplittedPath(leafValuePath);
566 LinkedHashMap<String, Property> properties = group.getProperties();
567 return PropertyUtils.processProperties(split, properties);
571 //Sunny flow - covered with UT
572 public List<NodeTemplate> getCpListByVf(String vfCustomizationId) {
573 List<NodeTemplate> cpList = new ArrayList<>();
574 if (GeneralUtility.isEmptyString(vfCustomizationId)) {
575 log.error("getCpListByVf vfCustomizationId string is empty");
579 List<NodeTemplate> serviceVfList = getServiceVfList();
580 if (serviceVfList == null || serviceVfList.isEmpty()) {
581 log.error("getCpListByVf Vfs not exist for vfCustomizationId {}", vfCustomizationId);
584 NodeTemplate vfInstance = getNodeTemplateByCustomizationUuid(serviceVfList, vfCustomizationId);
585 if (vfInstance == null) {
586 log.debug("getCpListByVf vf list is null");
589 cpList = getNodeTemplateBySdcType(vfInstance, SdcTypes.CP);
590 if (cpList == null || cpList.isEmpty())
591 log.debug("getCpListByVf cps not exist for vfCustomizationId {}", vfCustomizationId);
596 //Sunny flow - covered with UT
597 public List<NodeTemplate> getMembersOfVfModule(NodeTemplate vf, Group serviceLevelVfModule) {
599 log.error("getMembersOfVfModule - vf is null");
600 return new ArrayList<>();
603 if (serviceLevelVfModule == null || serviceLevelVfModule.getMetadata() == null || serviceLevelVfModule.getMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_VFMODULEMODELINVARIANTUUID) == null) {
604 log.error("getMembersOfVfModule - vfModule or its metadata is null. Cannot match a VF group based on invariantUuid from missing metadata.");
605 return new ArrayList<>();
609 SubstitutionMappings substitutionMappings = vf.getSubMappingToscaTemplate();
610 if (substitutionMappings != null) {
611 List<Group> groups = substitutionMappings.getGroups();
612 if (groups != null) {
613 Optional<Group> findFirst = groups
615 .filter(x -> (x.getMetadata() != null && serviceLevelVfModule.getMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_VFMODULEMODELINVARIANTUUID).equals(x.getMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_VFMODULEMODELINVARIANTUUID)))).findFirst();
616 if (findFirst.isPresent()) {
617 List<String> members = findFirst.get().getMembers();
618 if (members != null) {
619 return substitutionMappings.getNodeTemplates().stream().filter(x -> members.contains(x.getName())).collect(toList());
624 return new ArrayList<>();
628 public List<Pair<NodeTemplate, NodeTemplate>> getNodeTemplatePairsByReqName(
629 List<NodeTemplate> listOfReqNodeTemplates, List<NodeTemplate> listOfCapNodeTemplates, String reqName) {
631 if (listOfReqNodeTemplates == null) {
632 log.error("getNodeTemplatePairsByReqName - listOfReqNodeTemplates is null");
633 return new ArrayList<>();
636 if (listOfCapNodeTemplates == null) {
637 log.error("getNodeTemplatePairsByReqName - listOfCapNodeTemplates is null");
638 return new ArrayList<>();
641 if (GeneralUtility.isEmptyString(reqName)) {
642 log.error("getNodeTemplatePairsByReqName - reqName is null or empty");
643 return new ArrayList<>();
646 List<Pair<NodeTemplate, NodeTemplate>> pairsList = new ArrayList<>();
648 for (NodeTemplate reqNodeTemplate : listOfReqNodeTemplates) {
649 List<RequirementAssignment> requirements = reqNodeTemplate.getRequirements().getRequirementsByName(reqName).getAll();
650 for (RequirementAssignment reqEntry : requirements) {
651 String node = reqEntry.getNodeTemplateName();
653 Optional<NodeTemplate> findFirst = listOfCapNodeTemplates.stream().filter(x -> x.getName().equals(node)).findFirst();
654 if (findFirst.isPresent()) {
655 pairsList.add(new ImmutablePair<NodeTemplate, NodeTemplate>(reqNodeTemplate, findFirst.get()));
665 //Sunny flow - covered with UT
666 public List<NodeTemplate> getAllottedResources() {
667 List<NodeTemplate> nodeTemplates = null;
668 nodeTemplates = toscaTemplate.getTopologyTemplate().getNodeTemplates();
669 if (nodeTemplates.isEmpty()) {
670 log.error("getAllottedResources nodeTemplates not exist");
672 nodeTemplates = nodeTemplates.stream().filter(
673 x -> x.getMetaData() != null && x.getMetaData().getValue("category").equals("Allotted Resource"))
675 if (nodeTemplates.isEmpty()) {
676 log.debug("getAllottedResources - allotted resources not exist");
678 return nodeTemplates;
682 //Sunny flow - covered with UT
683 public String getTypeOfNodeTemplate(NodeTemplate nodeTemplate) {
684 if (nodeTemplate == null) {
686 log.error("getTypeOfNodeTemplate nodeTemplate is null");
689 return nodeTemplate.getTypeDefinition().getType();
693 * This methdd is returning the csarConformanceLevel for input CSAR
694 * When csarConformanceLevel is configured with failOnError as False in Error Configuration; it
695 * assigns the default value to csarConformanceLevel which is the max level provided in
697 * @return csarConformanceLevel
700 public String getConformanceLevel() {
701 LinkedHashMap<String, Object> csarMeta = toscaTemplate.getMetaProperties("csar.meta");
702 if (csarMeta == null){
703 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.");
704 if (configurationManager != null && !configurationManager.getErrorConfiguration()
705 .getErrorInfo("CONFORMANCE_LEVEL_ERROR").getFailOnError()){
706 String csarConLevel = configurationManager.getConfiguration().getConformanceLevel().getMaxVersion();
707 log.warn("csarConformanceLevel is not found in input csar; defaulting to max version {}" , csarConLevel);
711 log.warn("csarConformanceLevel is not found in input csar; returning null as no defaults defined in error configuration");
716 Object conformanceLevel = csarMeta.get("SDC-TOSCA-Definitions-Version");
717 if (conformanceLevel != null){
718 String confLevelStr = conformanceLevel.toString();
719 log.debug("CSAR conformance level is {}", confLevelStr);
722 log.error("Invalid csar.meta file - no entry found for SDC-TOSCA-Definitions-Version key. This entry should hold the conformance level.");
729 public String getNodeTemplateCustomizationUuid(NodeTemplate nt) {
731 if (nt != null && nt.getMetaData() != null){
732 res = nt.getMetaData().getValue(CUSTOMIZATION_UUID);
734 log.error("Node template or its metadata is null");
739 public List<NodeTemplate> getNodeTemplateBySdcType(NodeTemplate parentNodeTemplate, SdcTypes sdcType) {
740 return getNodeTemplateBySdcType(parentNodeTemplate, sdcType, false);
743 public boolean isNodeTypeSupported(NodeTemplate nodeTemplate) {
744 SdcTypes[] supportedTypes = SdcTypes.values();
745 return Arrays.stream(supportedTypes)
746 .anyMatch(v->nodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_TYPE)
747 .equals(v.getValue()));
750 private List<NodeTemplate> getNodeTemplateBySdcType(NodeTemplate parentNodeTemplate, SdcTypes sdcType, boolean isVNF) {
752 if (parentNodeTemplate == null) {
753 log.error("getNodeTemplateBySdcType - nodeTemplate is null or empty");
754 return new ArrayList<>();
757 if (sdcType == null) {
758 log.error("getNodeTemplateBySdcType - sdcType is null or empty");
759 return new ArrayList<>();
762 SubstitutionMappings substitutionMappings = parentNodeTemplate.getSubMappingToscaTemplate();
764 if (substitutionMappings != null) {
765 List<NodeTemplate> nodeTemplates = substitutionMappings.getNodeTemplates();
766 if (nodeTemplates != null && !nodeTemplates.isEmpty()) {
767 if (sdcType.equals(SdcTypes.VFC) && isVNF) {
768 return nodeTemplates.stream()
769 .filter(x -> (x.getMetaData() != null &&
770 sdcType.getValue().equals(x.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_TYPE))) && isVNFType(x))
774 return nodeTemplates.stream()
775 .filter(x -> (x.getMetaData() != null &&
776 sdcType.getValue().equals(x.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_TYPE))) && !isVNFType(x))
781 log.debug("getNodeTemplateBySdcType - SubstitutionMappings' node Templates not exist");
784 log.debug("getNodeTemplateBySdcType - SubstitutionMappings not exist");
786 return new ArrayList<>();
789 public Map<String, String> filterNodeTemplatePropertiesByValue(NodeTemplate nodeTemplate, FilterType filterType, String pattern) {
790 Map<String, String> filterMap = new HashMap<>();
792 if (nodeTemplate == null) {
793 log.error("filterNodeTemplatePropertiesByValue nodeTemplate is null");
797 if (filterType == null) {
798 log.error("filterNodeTemplatePropertiesByValue filterType is null");
802 if (GeneralUtility.isEmptyString(pattern)) {
803 log.error("filterNodeTemplatePropertiesByValue pattern string is empty");
807 Map<String, Property> ntProperties = nodeTemplate.getProperties();
809 if (ntProperties != null && ntProperties.size() > 0) {
811 for (Property current : ntProperties.values()) {
812 if (current.getValue() != null) {
813 filterProperties(current.getValue(), current.getName(), filterType, pattern, filterMap);
818 log.trace("filterNodeTemplatePropertiesByValue - filterMap value: {}", filterMap);
823 public NodeTemplate getVnfConfig(String vfCustomizationUuid) {
825 if (GeneralUtility.isEmptyString(vfCustomizationUuid)) {
826 log.error("getVnfConfig - vfCustomizationId - is null or empty");
830 List<NodeTemplate> serviceVfList = getServiceVfList();
831 NodeTemplate vfInstance = getNodeTemplateByCustomizationUuid(serviceVfList, vfCustomizationUuid);
832 return getNodeTemplateBySdcType(vfInstance, SdcTypes.VFC, true).stream().findAny().orElse(null);
836 public boolean hasTopology(NodeTemplate nodeTemplate) {
837 if (nodeTemplate == null) {
838 log.error("hasTopology - nodeTemplate - is null");
842 if (nodeTemplate.getMetaData() != null) {
843 String type = nodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_TYPE);
844 log.debug("hasTopology - node template {} is a {} type", nodeTemplate.getName(), type);
845 return SdcTypes.isComplex(type);
852 public List<NodeTemplate> getNodeTemplateChildren(NodeTemplate nodeTemplate) {
853 if (nodeTemplate == null) {
854 log.error("getNodeTemplateChildren - nodeTemplate - is null");
855 return new ArrayList<>();
858 SubstitutionMappings substitutionMappings = nodeTemplate.getSubMappingToscaTemplate();
859 if (substitutionMappings != null) {
860 List<NodeTemplate> nodeTemplates = substitutionMappings.getNodeTemplates();
861 if (nodeTemplates != null && !nodeTemplates.isEmpty()) {
863 return nodeTemplates.stream()
864 .filter(x -> !isVNFType(x))
868 log.debug("getNodeTemplateChildren - SubstitutionMappings' node Templates not exist");
871 log.debug("getNodeTemplateChildren - SubstitutionMappings not exist");
873 return new ArrayList<>();
877 public NodeTemplate getServiceNodeTemplateByNodeName(String nodeName) {
878 if (GeneralUtility.isEmptyString(nodeName)) {
879 log.error("getServiceNodeTemplateByNodeName - nodeName - is null or empty");
883 List<NodeTemplate> nodeTemplates = getServiceNodeTemplates();
884 Optional<NodeTemplate> findFirst = nodeTemplates.stream().filter(nt -> nt.getName().equals(nodeName)).findFirst();
886 return findFirst.isPresent() ? findFirst.get() : null;
890 public Metadata getNodeTemplateMetadata(NodeTemplate nt) {
892 log.error("getNodeTemplateMetadata - nt (node template) - is null");
896 return nt.getMetaData();
900 public CapabilityAssignments getCapabilitiesOf(NodeTemplate nt) {
902 log.error("getCapabilitiesOf - nt (node template) - is null");
906 return nt.getCapabilities();
910 public RequirementAssignments getRequirementsOf(NodeTemplate nt) {
912 log.error("getRequirementsOf - nt (node template) - is null");
916 return nt.getRequirements();
920 public String getCapabilityPropertyLeafValue(CapabilityAssignment capability, String pathToPropertyLeafValue) {
921 if (capability == null) {
922 log.error("getCapabilityPropertyLeafValue - capability is null");
926 if (GeneralUtility.isEmptyString(pathToPropertyLeafValue)) {
927 log.error("getCapabilityPropertyLeafValue - pathToPropertyLeafValue is null or empty");
931 String[] split = getSplittedPath(pathToPropertyLeafValue);
932 LinkedHashMap<String, Property> properties = capability.getProperties();
933 Object property = PropertyUtils.processProperties(split, properties);
934 return property == null || property instanceof Function ? null : String.valueOf(property);
938 public ArrayList<Group> getGroupsOfOriginOfNodeTemplate(NodeTemplate nodeTemplate) {
939 if(StringUtils.isNotEmpty(nodeTemplate.getName())){
940 return getNodeTemplateByName(nodeTemplate.getName()).getSubMappingToscaTemplate().getGroups();
942 return new ArrayList<>();
946 public ArrayList<Group> getGroupsOfTopologyTemplateByToscaGroupType(String groupType) {
947 if(toscaTemplate.getGroups() == null)
948 return new ArrayList<>();
949 return (ArrayList<Group>) toscaTemplate.getGroups()
951 .filter(g->g.getType().equals(groupType))
952 .sorted(Group::compareTo)
957 public ArrayList<Group> getGroupsOfTopologyTemplate() {
958 return toscaTemplate.getGroups() == null ? new ArrayList<>() : toscaTemplate.getGroups();
962 public ArrayList<Group> getGroupsOfOriginOfNodeTemplateByToscaGroupType(NodeTemplate nodeTemplate, String groupType) {
963 return (ArrayList<Group>) getGroupsOfOriginOfNodeTemplate(nodeTemplate)
965 .filter(g->g.getType().equals(groupType))
966 .sorted(Group::compareTo)
971 public List<NodeTemplate> getGroupMembersFromTopologyTemplate(String groupName) {
972 if(toscaTemplate.getNodeTemplates() == null){
973 return new ArrayList<>();
975 List<String> membersNames = getGroupMembers(groupName);
976 return toscaTemplate.getNodeTemplates().stream()
977 .filter(nt->membersNames.contains(nt.getName()))
983 public List<NodeTemplate> getGroupMembersOfOriginOfNodeTemplate(NodeTemplate nodeTemplate, String groupName) {
984 ArrayList<Group> groups = getGroupsOfOriginOfNodeTemplate(nodeTemplate);
985 if(!groups.isEmpty()){
986 Optional<Group> group = groups.stream().filter(g -> g.getName().equals(groupName)).findFirst();
987 if(group.isPresent()){
988 return nodeTemplate.getSubMappingToscaTemplate().getNodeTemplates().stream()
989 .filter(nt -> group.get().getMembers().contains(nt.getName()))
993 return new ArrayList<>();
996 public List<NodeTemplate> getServiceNodeTemplateBySdcType(SdcTypes sdcType) {
997 if (sdcType == null) {
998 log.error("getServiceNodeTemplateBySdcType - sdcType is null or empty");
999 return new ArrayList<>();
1002 TopologyTemplate topologyTemplate = toscaTemplate.getTopologyTemplate();
1003 return getNodeTemplateBySdcType(topologyTemplate, sdcType);
1006 /************************************* helper functions ***********************************/
1007 private boolean isVNFType(NodeTemplate nt) {
1008 return nt.getType().endsWith("VnfConfiguration");
1011 @SuppressWarnings("unchecked")
1012 private Map<String, String> filterProperties(Object property, String path, FilterType filterType, String pattern, Map<String, String> filterMap) {
1014 if (property instanceof Map) {
1015 for (Map.Entry<String, Object> item: ((Map<String, Object>) property).entrySet()) {
1016 String itemPath = path + PATH_DELIMITER + item.getKey();
1017 filterProperties(item.getValue(), itemPath, filterType, pattern, filterMap);
1019 } else if (property instanceof List) {
1020 for (Object item: (List<Object>)property) {
1021 filterProperties(item, path, filterType, pattern, filterMap);
1024 if (filterType.isMatch(property.toString(), pattern)) {
1025 filterMap.put(path, property.toString());
1032 /************************************* helper functions ***********************************/
1033 private List<NodeTemplate> getNodeTemplateBySdcType(TopologyTemplate topologyTemplate, SdcTypes sdcType) {
1034 if (sdcType == null) {
1035 log.error("getNodeTemplateBySdcType - sdcType is null or empty");
1036 return new ArrayList<>();
1039 if (topologyTemplate == null) {
1040 log.error("getNodeTemplateBySdcType - topologyTemplate is null");
1041 return new ArrayList<>();
1044 List<NodeTemplate> nodeTemplates = topologyTemplate.getNodeTemplates();
1046 if (nodeTemplates != null && !nodeTemplates.isEmpty())
1047 return nodeTemplates.stream().filter(x -> (x.getMetaData() != null && sdcType.getValue().equals(x.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_TYPE)))).collect(toList());
1049 log.debug("getNodeTemplateBySdcType - topologyTemplate's nodeTemplates not exist");
1050 return new ArrayList<>();
1053 //Assumed to be unique property for the list
1054 private NodeTemplate getNodeTemplateByCustomizationUuid(List<NodeTemplate> nodeTemplates, String customizationId) {
1055 if (customizationId != null) {
1056 Optional<NodeTemplate> findFirst = nodeTemplates.stream().filter(x -> (x.getMetaData() != null && customizationId.equals(x.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID)))).findFirst();
1057 return findFirst.isPresent() ? findFirst.get() : null;
1060 log.error("getNodeTemplateByCustomizationUuid - customizationId is null");
1066 public Map<String, List<InterfacesDef>> getInterfacesOf(NodeTemplate nt){
1070 return nt.getAllInterfaceDetailsForNodeType();
1074 public List<String> getInterfaces(NodeTemplate nt){
1075 Map<String, List<InterfacesDef>> interfaceDetails = nt.getAllInterfaceDetailsForNodeType();
1076 return new ArrayList<>(interfaceDetails.keySet());
1080 public List<InterfacesDef> getInterfaceDetails(NodeTemplate nt, String interfaceName){
1081 Map<String, List<InterfacesDef>> interfaceDetails = nt.getAllInterfaceDetailsForNodeType();
1082 return interfaceDetails.get(interfaceName);
1086 public List<String> getAllInterfaceOperations(NodeTemplate nt, String interfaceName){
1087 Map<String, List<InterfacesDef>> interfaceDetails = nt.getAllInterfaceDetailsForNodeType();
1088 return interfaceDetails.values().stream().flatMap(List::stream).map(val -> val.getOperationName()).collect(
1089 Collectors.toList());
1093 public InterfacesDef getInterfaceOperationDetails(NodeTemplate nt, String interfaceName, String operationName){
1094 Map<String, List<InterfacesDef>> interfaceDetails = nt.getAllInterfaceDetailsForNodeType();
1095 if(!interfaceDetails.isEmpty()){
1096 List<InterfacesDef> interfaceDefs = interfaceDetails.get(interfaceName);
1097 return interfaceDefs.stream().filter(val -> val.getOperationName().equals(operationName)).findFirst().orElse(null);
1103 public List<String> getPropertyLeafValueByPropertyNamePathAndNodeTemplatePath(String propertyNamePath, String nodeTemplatePath) {
1104 log.info("A new request is received: property path is [{}], node template path is [{}]",
1105 propertyNamePath, nodeTemplatePath);
1107 List<String> propertyValuesList;
1109 if (StringUtils.isEmpty(nodeTemplatePath) || StringUtils.isEmpty(propertyNamePath)) {
1110 log.error("One of parameters is empty or null: property path is [{}], node template path is [{}]",
1111 propertyNamePath, nodeTemplatePath);
1112 propertyValuesList = Collections.emptyList();
1115 String[] nodeTemplates = getSplittedPath(nodeTemplatePath);
1116 propertyValuesList = getPropertyFromInternalNodeTemplate(getNodeTemplateByName(nodeTemplates[0]), 1, nodeTemplates, propertyNamePath);
1117 log.info("Found property value {} by path [{}] for node template [{}]",
1118 propertyValuesList, propertyNamePath, nodeTemplatePath);
1120 return propertyValuesList;
1123 private List<String> getPropertyFromInternalNodeTemplate(NodeTemplate parent, int index,
1124 String[] nodeTemplatePath, String propertyPath) {
1125 List<String> propertyValuesList;
1126 if (parent == null) {
1127 log.error("Node template {} is not found, the request will be rejected", nodeTemplatePath[index]);
1128 propertyValuesList = Collections.emptyList();
1130 else if (nodeTemplatePath.length <= index) {
1131 log.debug("Stop NODE TEMPLATE searching");
1132 propertyValuesList = getSimpleOrListPropertyValue(parent, propertyPath);
1135 log.debug("Node template {} is found with name {}", nodeTemplatePath[index], parent.getName());
1136 NodeTemplate childNT = getChildNodeTemplateByName(parent, nodeTemplatePath[index]);
1138 if (childNT == null || !isNodeTypeSupported(childNT)) {
1139 log.error("Unsupported or not found node template named {}, the request will be rejected",
1140 nodeTemplatePath[index]);
1141 propertyValuesList = Collections.emptyList();
1144 propertyValuesList = getPropertyFromInternalNodeTemplate(childNT, index + 1, nodeTemplatePath,
1148 return propertyValuesList;
1153 private List<String> getSimpleOrListPropertyValue(NodeTemplate nodeTemplate, String propertyPath) {
1154 List<String> propertyValueList;
1155 String[] path = getSplittedPath(propertyPath);
1156 Property property = getNodeTemplatePropertyObjectByName(nodeTemplate, path[0]);
1158 if (PropertyUtils.isPropertyTypeSimpleOrListOfSimpleTypes(nodeTemplate, path, property)) {
1159 //the requested property type is either simple or list of simple types
1160 PropertySchemaType propertyType = PropertySchemaType.getEnumByValue(property.getType());
1161 if (propertyType == PropertySchemaType.LIST &&
1162 PropertyUtils.isDataPropertyType((String)property.getEntrySchema()
1163 .get(SdcPropertyNames.PROPERTY_NAME_TYPE))) {
1164 //cover the case when a type of property "path[0]' is list of data types
1165 // and the requested property is an internal simple property of this data type
1166 propertyValueList = calculatePropertyValue(getNodeTemplatePropertyValueAsObject(nodeTemplate, path[0]), path, nodeTemplate.getName());
1169 //the requested property is simple type or list of simple types
1170 propertyValueList = calculatePropertyValue(getNodeTemplatePropertyValueAsObject(nodeTemplate, propertyPath), null, nodeTemplate.getName());
1174 log.error("The type of property {} on node {} is neither simple nor list of simple objects, the request will be rejected",
1175 propertyPath, nodeTemplate.getName());
1176 propertyValueList = Collections.emptyList();
1178 return propertyValueList;
1181 private List<String> calculatePropertyValue(Object valueAsObject, String path[], String nodeName) {
1182 if (valueAsObject == null || valueAsObject instanceof Map) {
1183 log.error("The property {} either is not found on node template [{}], or it is data type, or it is not resolved get_input", path, nodeName);
1184 return Collections.emptyList();
1187 return PropertyUtils.findSimplePropertyValueInListOfDataTypes((List<Object>)valueAsObject, path);
1189 return PropertyUtils.buildSimplePropertValueOrList(valueAsObject);
1195 private Property getNodeTemplatePropertyObjectByName(NodeTemplate nodeTemplate, String propertyName) {
1196 return nodeTemplate.getPropertiesObjects()
1198 .filter(p->p.getName().equals(propertyName))
1203 private NodeTemplate getChildNodeTemplateByName(NodeTemplate parent, String nodeTemplateName) {
1204 return getNodeTemplateChildren(parent)
1206 .filter(nt->nt.getName().equals(nodeTemplateName))
1207 .findFirst().orElse(null);
1211 public List<Input> getInputsWithAnnotations() {
1212 return toscaTemplate.getInputs(true);
1216 public List<IEntityDetails> getEntity(EntityQuery entityQuery, TopologyTemplateQuery topologyTemplateQuery, boolean isRecursive) {
1218 if (log.isDebugEnabled()) {
1219 log.debug("getEntity request: EntityQuery <{}>, TopologyTemplateQuery <{}>, isRecursive<{}>",
1220 entityQuery, topologyTemplateQuery, isRecursive);
1222 return new QueryProcessor(toscaTemplate, entityQuery, topologyTemplateQuery, isRecursive).doQuery();
1226 public HashSet<DataType> getDataTypes() {
1227 return toscaTemplate.getDataTypes();