2 * ============LICENSE_START=======================================================
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.openecomp.sdc.be.tosca;
23 import static org.apache.commons.collections.CollectionUtils.isNotEmpty;
24 import static org.apache.commons.lang3.StringUtils.isBlank;
25 import static org.apache.commons.lang3.StringUtils.isNoneBlank;
27 import com.google.common.collect.Iterables;
28 import com.google.common.collect.Maps;
29 import fj.data.Either;
30 import java.util.ArrayList;
31 import java.util.Collections;
32 import java.util.HashMap;
33 import java.util.Iterator;
34 import java.util.List;
36 import java.util.Optional;
37 import java.util.function.Function;
38 import java.util.stream.Collectors;
39 import org.apache.commons.collections.CollectionUtils;
40 import org.apache.commons.collections.MapUtils;
41 import org.apache.commons.lang3.StringUtils;
42 import org.apache.commons.lang3.tuple.ImmutablePair;
43 import org.openecomp.sdc.be.datatypes.elements.CapabilityDataDefinition;
44 import org.openecomp.sdc.be.datatypes.elements.RequirementDataDefinition;
45 import org.openecomp.sdc.be.datatypes.enums.OriginTypeEnum;
46 import org.openecomp.sdc.be.model.CapabilityDefinition;
47 import org.openecomp.sdc.be.model.Component;
48 import org.openecomp.sdc.be.model.ComponentInstance;
49 import org.openecomp.sdc.be.model.ComponentInstanceProperty;
50 import org.openecomp.sdc.be.model.ComponentParametersView;
51 import org.openecomp.sdc.be.model.DataTypeDefinition;
52 import org.openecomp.sdc.be.model.GroupDefinition;
53 import org.openecomp.sdc.be.model.PropertyDefinition;
54 import org.openecomp.sdc.be.model.RequirementDefinition;
55 import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade;
56 import org.openecomp.sdc.be.model.jsonjanusgraph.utils.ModelConverter;
57 import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
58 import org.openecomp.sdc.be.model.utils.ComponentUtilities;
59 import org.openecomp.sdc.be.tosca.ToscaUtils.SubstitutionEntry;
60 import org.openecomp.sdc.be.tosca.model.SubstitutionMapping;
61 import org.openecomp.sdc.be.tosca.model.ToscaCapability;
62 import org.openecomp.sdc.be.tosca.model.ToscaNodeTemplate;
63 import org.openecomp.sdc.be.tosca.model.ToscaNodeType;
64 import org.openecomp.sdc.be.tosca.model.ToscaProperty;
65 import org.openecomp.sdc.be.tosca.model.ToscaRequirement;
66 import org.openecomp.sdc.be.tosca.model.ToscaTemplateCapability;
67 import org.openecomp.sdc.common.log.wrappers.Logger;
68 import org.springframework.beans.factory.annotation.Autowired;
69 import org.springframework.context.annotation.Scope;
72 * Allows to convert requirements\capabilities of a component to requirements\capabilities of a substitution mappings section of a tosca template
75 @org.springframework.stereotype.Component("capabilty-requirement-convertor")
76 @Scope(value = "singleton")
77 public class CapabilityRequirementConverter {
79 private static final String NO_CAPABILITIES = "No Capabilities for node type";
80 private static final String NO_REQUIREMENTS = "No Requirements for node type";
81 private static CapabilityRequirementConverter instance;
82 private static final Logger logger = Logger.getLogger(CapabilityRequirementConverter.class);
83 private static final String PATH_DELIMITER = ".";
84 private static final String FAILED_TO_FIND_CI_IN_PATH ="Failed to find ci in the path is {} component {}";
87 private ToscaOperationFacade toscaOperationFacade;
89 private PropertyConvertor propertyConvertor;
91 public CapabilityRequirementConverter() {}
93 public static synchronized CapabilityRequirementConverter getInstance() {
94 if (instance == null) {
95 instance = new CapabilityRequirementConverter();
100 public String buildCapabilityNameForComponentInstance( Map<String,Component> componentCache , ComponentInstance componentInstance, CapabilityDefinition c) {
101 String prefix = buildCapReqNamePrefix(componentInstance.getNormalizedName());
102 if(ComponentUtilities.isNotUpdatedCapReqName(prefix, c.getName(), c.getPreviousName())){
103 return buildSubstitutedName(componentCache, c.getName(), c.getPreviousName(), c.getPath(), c.getOwnerId(), componentInstance)
105 .orValue(c.getName());
107 return c.getPreviousName();
110 public String buildRequirementNameForComponentInstance(Map<String,Component> componentCache,
111 ComponentInstance componentInstance,
112 RequirementDefinition r) {
113 String prefix = buildCapReqNamePrefix(componentInstance.getNormalizedName());
114 if (ComponentUtilities.isNotUpdatedCapReqName(prefix, r.getName(), r.getPreviousName())) {
115 return buildSubstitutedName(componentCache, r.getName(), r.getPreviousName(), r.getPath(), r.getOwnerId(),
116 componentInstance).left()
117 .orValue(r.getName());
119 return r.getPreviousName();
122 private String buildCapReqNamePrefix(String normalizedName) {
123 return normalizedName + PATH_DELIMITER;
127 * Allows to convert capabilities of a component to capabilities of a substitution mappings section of a tosca template
128 * @param componentInstance
130 * @param nodeTemplate
133 public Either<ToscaNodeTemplate, ToscaError> convertComponentInstanceCapabilities(ComponentInstance componentInstance, Map<String, DataTypeDefinition> dataTypes, ToscaNodeTemplate nodeTemplate) {
135 Map<String, List<CapabilityDefinition>> capabilitiesInst = componentInstance.getCapabilities();
136 Map<String,Component> componentCache = new HashMap<>();
137 if (capabilitiesInst != null && !capabilitiesInst.isEmpty()) {
138 Map<String, ToscaTemplateCapability> capabilities = new HashMap<>();
139 capabilitiesInst.entrySet().forEach( e -> {
140 List<CapabilityDefinition> capList = e.getValue();
141 if ( capList != null && !capList.isEmpty() ) {
143 .forEach( c -> convertOverridenProperties( componentInstance, dataTypes, capabilities, c ,
144 buildCapabilityNameForComponentInstance( componentCache , componentInstance , c )));
147 if (MapUtils.isNotEmpty(capabilities)) {
148 nodeTemplate.setCapabilities(capabilities);
151 return Either.left(nodeTemplate);
154 private void convertOverridenProperties(ComponentInstance componentInstance, Map<String, DataTypeDefinition> dataTypes, Map<String, ToscaTemplateCapability> capabilties, CapabilityDefinition c , String capabilityName) {
155 if (isNotEmpty(c.getProperties())) {
158 .filter(p -> p.getValue() != null || p.getDefaultValue() != null)
159 .forEach(p -> convertOverriddenProperty(componentInstance, dataTypes, capabilties , p ,capabilityName));
163 private void convertOverriddenProperty(ComponentInstance componentInstance, Map<String, DataTypeDefinition> dataTypes, Map<String, ToscaTemplateCapability> capabilties, ComponentInstanceProperty p , String capabilityName) {
164 if (logger.isDebugEnabled()) {
165 logger.debug("Exist d property {} for capability {} with value {}", p.getName(), capabilityName, p.getValue());
167 ToscaTemplateCapability toscaTemplateCapability = capabilties.computeIfAbsent( capabilityName , key -> new ToscaTemplateCapability() );
169 Map<String, Object> toscaCapProp = toscaTemplateCapability.getProperties();
170 if (toscaCapProp == null) {
171 toscaCapProp = new HashMap<>();
173 Object convertedValue = convertInstanceProperty(dataTypes, componentInstance, p);
174 toscaCapProp.put(p.getName(), convertedValue);
175 toscaTemplateCapability.setProperties(toscaCapProp);
178 private Object convertInstanceProperty(Map<String, DataTypeDefinition> dataTypes, ComponentInstance componentInstance, ComponentInstanceProperty prop) {
179 logger.debug("Convert property {} for instance {}", prop.getName(), componentInstance.getUniqueId());
180 String propValue = prop.getValue() == null ? prop.getDefaultValue() : prop.getValue();
181 return propertyConvertor.convertToToscaObject(prop, propValue, dataTypes, false);
184 * Allows to convert requirements of a node type to tosca template requirements representation
189 public Either<ToscaNodeType, ToscaError> convertRequirements(Map<String, Component> componentsCache, Component component, ToscaNodeType nodeType) {
190 List<Map<String, ToscaRequirement>> toscaRequirements = convertRequirementsAsList(componentsCache, component);
191 if (!toscaRequirements.isEmpty()) {
192 nodeType.setRequirements(toscaRequirements);
194 logger.debug("Finish convert Requirements for node type");
196 return Either.left(nodeType);
200 * Allows to convert component requirements to the tosca template substitution mappings requirements
201 * @param componentsCache
203 * @param substitutionMappings
206 public Either<SubstitutionMapping, ToscaError> convertSubstitutionMappingRequirements(Map<String,Component> componentsCache, Component component, SubstitutionMapping substitutionMappings) {
207 Either<SubstitutionMapping, ToscaError> result = Either.left(substitutionMappings);
208 Either<Map<String, String[]>, ToscaError> toscaRequirementsRes = convertSubstitutionMappingRequirementsAsMap(componentsCache, component);
209 if(toscaRequirementsRes.isRight()){
210 result = Either.right(toscaRequirementsRes.right().value());
211 logger.debug("Failed convert requirements for the component {}. ", component.getName());
212 } else if (MapUtils.isNotEmpty(toscaRequirementsRes.left().value())) {
213 substitutionMappings.setRequirements(toscaRequirementsRes.left().value());
214 result = Either.left(substitutionMappings);
215 logger.debug("Finish convert requirements for the component {}. ", component.getName());
221 * Allows to convert requirements of a server proxy node type to tosca template requirements
222 * @param instanceProxy
223 * @return converted tosca template requirements
225 List<Map<String, ToscaRequirement>> convertProxyRequirements(Map<String, Component> componentCache,
226 ComponentInstance instanceProxy) {
227 Map<String, List<RequirementDefinition>> requirements = instanceProxy.getRequirements();
228 List<Map<String, ToscaRequirement>> toscaRequirements = new ArrayList<>();
229 if (requirements != null) {
230 requirements.entrySet().stream()
231 .flatMap(e -> e.getValue().stream())
233 ImmutablePair<String, ToscaRequirement> pair = convertProxyRequirement(
234 buildRequirementNameForComponentInstance(componentCache, instanceProxy, req), req);
235 Map<String, ToscaRequirement> requirement = new HashMap<>();
236 requirement.put(pair.left, pair.right);
237 toscaRequirements.add(requirement);
240 logger.debug(NO_REQUIREMENTS);
243 return toscaRequirements;
246 private ImmutablePair<String, ToscaRequirement> convertProxyRequirement(String requirementName,
247 RequirementDefinition r) {
248 ToscaRequirement toscaRequirement = createToscaRequirement(r);
249 return new ImmutablePair<>(requirementName, toscaRequirement);
252 private List<Map<String, ToscaRequirement>> convertRequirementsAsList(Map<String, Component> componentsCache, Component component) {
253 Map<String, List<RequirementDefinition>> requirements = component.getRequirements();
254 List<Map<String, ToscaRequirement>> toscaRequirements = new ArrayList<>();
255 if (requirements != null) {
256 for (Map.Entry<String, List<RequirementDefinition>> entry : requirements.entrySet()) {
257 entry.getValue().stream().filter(r -> filter(component, r.getOwnerId())).forEach(r -> {
258 ImmutablePair<String, ToscaRequirement> pair = convertRequirement(componentsCache, component, ModelConverter.isAtomicComponent(component), r);
259 Map<String, ToscaRequirement> requirement = new HashMap<>();
261 requirement.put(pair.left, pair.right);
262 toscaRequirements.add(requirement);
264 logger.debug("Finish convert Requirements for node type");
267 logger.debug(NO_REQUIREMENTS);
269 return toscaRequirements;
272 private boolean filter(Component component, String ownerId) {
273 return !ModelConverter.isAtomicComponent(component) || isNodeTypeOwner(component, ownerId) || (ModelConverter.isAtomicComponent(component) && ownerId == null);
276 private boolean isNodeTypeOwner(Component component, String ownerId) {
277 return ModelConverter.isAtomicComponent(component) && component.getUniqueId().equals(ownerId);
280 private String dropLast( String path, String delimiter ) {
281 if (isBlank(path) || isBlank(delimiter)){
284 return path.substring(0, path.lastIndexOf(delimiter));
287 private Either<Map<String, String[]>, ToscaError> convertSubstitutionMappingRequirementsAsMap(Map<String, Component> componentsCache, Component component) {
288 Map<String, List<RequirementDefinition>> requirements = component.getRequirements();
289 Either<Map<String, String[]>, ToscaError> result;
290 if (requirements != null) {
291 result = buildAddSubstitutionMappingsRequirements(componentsCache, component, requirements);
293 result = Either.left(Maps.newHashMap());
294 logger.debug("No requirements for substitution mappings section of a tosca template of the component {}. ", component.getName());
299 private Either<Map<String, String[]>, ToscaError> buildAddSubstitutionMappingsRequirements(Map<String, Component> componentsCache, Component component, Map<String, List<RequirementDefinition>> requirements) {
301 Map<String, String[]> toscaRequirements = new HashMap<>();
302 Either<Map<String, String[]>, ToscaError> result = null;
303 for (Map.Entry<String, List<RequirementDefinition>> entry : requirements.entrySet()) {
304 Optional<RequirementDefinition> failedToAddRequirement = entry.getValue()
305 .stream().filter(RequirementDefinition::isExternal)
306 .filter(r->!addEntry(componentsCache, toscaRequirements, component, new SubstitutionEntry(r.getName(), r.getParentName(), ""), r.getPreviousName(), r.getOwnerId(), r.getPath()))
308 if(failedToAddRequirement.isPresent()){
309 logger.debug("Failed to convert requirement {} for substitution mappings section of a tosca template of the component {}. ",
310 failedToAddRequirement.get().getName(), component.getName());
311 result = Either.right(ToscaError.NODE_TYPE_REQUIREMENT_ERROR);
313 logger.debug("Finish convert requirements for the component {}. ", component.getName());
316 result = Either.left(toscaRequirements);
321 private Either<Map<String, String[]>, ToscaError> buildAddSubstitutionMappingsCapabilities(Map<String, Component> componentsCache, Component component, Map<String, List<CapabilityDefinition>> capabilities) {
323 Map<String, String[]> toscaCapabilities = new HashMap<>();
324 Either<Map<String, String[]>, ToscaError> result = null;
325 for (Map.Entry<String, List<CapabilityDefinition>> entry : capabilities.entrySet()) {
326 Optional<CapabilityDefinition> failedToAddRequirement = entry.getValue()
328 .filter(c->!addEntry(componentsCache, toscaCapabilities, component, new SubstitutionEntry(c.getName(), c.getParentName(), ""), c.getPreviousName(), c.getOwnerId(), c.getPath()))
330 if(failedToAddRequirement.isPresent()){
331 logger.debug("Failed to convert capability {} for substitution mappings section of a tosca template of the component {}. ",
332 failedToAddRequirement.get().getName(), component.getName());
333 result = Either.right(ToscaError.NODE_TYPE_CAPABILITY_ERROR);
335 logger.debug("Finish convert capabilities for the component {}. ", component.getName());
338 result = Either.left(toscaCapabilities);
343 private boolean addEntry(Map<String, Component> componentsCache, Map<String, String[]> capReqMap, Component component, SubstitutionEntry entry, String previousName, String ownerId, List<String> path){
345 if(shouldBuildSubstitutionName(component, path) && !buildSubstitutedNamePerInstance(componentsCache, component, entry.getFullName(), previousName, path, ownerId, entry)){
348 logger.debug("The requirement/capability {} belongs to the component {} ", entry.getFullName(), component.getUniqueId());
349 if (StringUtils.isNotEmpty(entry.getSourceName())) {
350 addEntry(capReqMap, component, path, entry);
352 logger.debug("Finish convert the requirement/capability {} for the component {}. ", entry.getFullName(), component.getName());
357 private boolean shouldBuildSubstitutionName(Component component, List<String> path) {
358 return ToscaUtils.isNotComplexVfc(component) && isNotEmpty(path) && path.iterator().hasNext();
361 private boolean buildSubstitutedNamePerInstance(Map<String, Component> componentsCache, Component component, String name, String previousName, List<String> path, String ownerId, SubstitutionEntry entry) {
365 if(CollectionUtils.isNotEmpty(component.getGroups())) {
366 Optional<GroupDefinition> groupOpt = component.getGroups().stream().filter(g -> g.getUniqueId().equals(ownerId)).findFirst();
367 if (groupOpt.isPresent()) {
368 prefix = buildCapReqNamePrefix(groupOpt.get().getNormalizedName());
369 if(ComponentUtilities.isNotUpdatedCapReqName(prefix, name, previousName)){
371 fullName = prefix + sourceName;
373 sourceName = previousName;
376 entry.setFullName(fullName);
377 entry.setSourceName(sourceName);
378 entry.setOwner(groupOpt.get().getNormalizedName());
383 Optional<ComponentInstance> ci =
384 component.safeGetComponentInstances().stream().filter(c->c.getUniqueId().equals(Iterables.getLast(path))).findFirst();
386 logger.debug(FAILED_TO_FIND_CI_IN_PATH, path, component.getUniqueId());
388 Collections.reverse(path);
390 logger.debug("try to reverse path {} component {}", path, component.getUniqueId());
391 ci = component.safeGetComponentInstances().stream().filter(c->c.getUniqueId().equals(Iterables.getLast(path))).findFirst();
394 prefix = buildCapReqNamePrefix(ci.get().getNormalizedName());
395 if(ComponentUtilities.isNotUpdatedCapReqName(prefix, name, previousName)){
396 Either<String, Boolean> buildSubstitutedName = buildSubstitutedName(componentsCache, name, previousName, path, ownerId, ci.get());
397 if(buildSubstitutedName.isRight()){
398 logger.debug("Failed buildSubstitutedName name {} path {} component {}", name, path, component.getUniqueId());
401 sourceName = buildSubstitutedName.left().value();
402 fullName = prefix + sourceName;
404 sourceName = previousName;
407 entry.setFullName(fullName);
408 entry.setSourceName(sourceName);
410 logger.debug(FAILED_TO_FIND_CI_IN_PATH, path, component.getUniqueId());
416 private void addEntry(Map<String, String[]> toscaRequirements, Component component, List<String> capPath, SubstitutionEntry entry) {
417 Optional<ComponentInstance> findFirst = component.safeGetComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(Iterables.getLast(capPath))).findFirst();
418 findFirst.ifPresent(componentInstance -> entry.setOwner(componentInstance.getName()));
419 if (StringUtils.isNotEmpty(entry.getOwner()) && StringUtils.isNotEmpty(entry.getSourceName())) {
420 toscaRequirements.put(entry.getFullName(), new String[] { entry.getOwner(), entry.getSourceName() });
424 public Either<String, Boolean> buildSubstitutedName(Map<String, Component> componentsCache, String name, String previousName, List<String> path, String ownerId, ComponentInstance instance) {
425 if(StringUtils.isNotEmpty(previousName)){
426 return Either.left(name);
428 Either<Component, Boolean> getOriginRes = getOriginComponent(componentsCache, instance);
429 if(getOriginRes.isRight()){
430 logger.debug("Failed to build substituted name for the capability/requirement {}. Failed to get an origin component with uniqueId {}", name, instance.getComponentUid());
431 return Either.right(false);
433 List<String> reducedPath = ownerId !=null ? getReducedPathByOwner(path , ownerId ) : getReducedPath(path) ;
434 logger.debug("reducedPath for ownerId {}, reducedPath {} ", ownerId, reducedPath);
435 reducedPath.remove(reducedPath.size() - 1);
436 return buildSubstitutedName(componentsCache, getOriginRes.left().value(), reducedPath, name, previousName);
439 private String buildReqNamePerOwnerByPath(Map<String, Component> componentsCache, Component component, RequirementDefinition r) {
440 return buildCapReqNamePerOwnerByPath(componentsCache, component, r.getName(), r.getPreviousName(), r.getPath());
443 private ImmutablePair<String, ToscaRequirement> convertRequirement(Map<String, Component> componentsCache, Component component, boolean isNodeType, RequirementDefinition r) {
444 String name = r.getName();
445 if (!isNodeType && ToscaUtils.isNotComplexVfc(component)) {
446 name = buildReqNamePerOwnerByPath(componentsCache, component, r);
448 logger.debug("the requirement {} belongs to resource {} ", name, component.getUniqueId());
449 ToscaRequirement toscaRequirement = createToscaRequirement(r);
450 return new ImmutablePair<>(name, toscaRequirement);
453 private ToscaRequirement createToscaRequirement(RequirementDefinition r) {
454 ToscaRequirement toscaRequirement = new ToscaRequirement();
456 List<Object> occurrences = new ArrayList<>();
457 occurrences.add(Integer.valueOf(r.getMinOccurrences()));
458 if (r.getMaxOccurrences().equals(RequirementDataDefinition.MAX_OCCURRENCES)) {
459 occurrences.add(r.getMaxOccurrences());
461 occurrences.add(Integer.valueOf(r.getMaxOccurrences()));
463 toscaRequirement.setOccurrences(occurrences);
464 toscaRequirement.setNode(r.getNode());
465 toscaRequirement.setCapability(r.getCapability());
466 toscaRequirement.setRelationship(r.getRelationship());
467 return toscaRequirement;
471 * Allows to convert capabilities of a node type to tosca template capabilities
476 public Map<String, ToscaCapability> convertCapabilities(Map<String, Component> componentsCache, Component component, Map<String, DataTypeDefinition> dataTypes) {
477 Map<String, List<CapabilityDefinition>> capabilities = component.getCapabilities();
478 Map<String, ToscaCapability> toscaCapabilities = new HashMap<>();
479 if (capabilities != null) {
480 boolean isNodeType = ModelConverter.isAtomicComponent(component);
481 for (Map.Entry<String, List<CapabilityDefinition>> entry : capabilities.entrySet()) {
482 entry.getValue().stream().filter(c -> filter(component, c.getOwnerId())).forEach(c -> convertCapability(componentsCache, component, toscaCapabilities, isNodeType, c, dataTypes , c.getName()));
485 logger.debug(NO_CAPABILITIES);
488 return toscaCapabilities;
492 * Allows to convert capabilities of a server proxy node type to tosca template capabilities
493 * @param instanceProxy
497 public Map<String, ToscaCapability> convertProxyCapabilities(Map<String, Component> componentCache,
498 ComponentInstance instanceProxy,
499 Map<String, DataTypeDefinition> dataTypes) {
500 Map<String, List<CapabilityDefinition>> capabilities = instanceProxy.getCapabilities();
501 Map<String, ToscaCapability> toscaCapabilities = new HashMap<>();
502 if (capabilities != null) {
503 for (Map.Entry<String, List<CapabilityDefinition>> entry : capabilities.entrySet()) {
506 .forEach(c -> convertProxyCapability(toscaCapabilities, c, dataTypes ,
507 buildCapabilityNameForComponentInstance( componentCache , instanceProxy , c )));
510 logger.debug(NO_CAPABILITIES);
513 return toscaCapabilities;
517 * Allows to convert component capabilities to the tosca template substitution mappings capabilities
518 * @param componentsCache
522 public Either<Map<String, String[]>, ToscaError> convertSubstitutionMappingCapabilities(Map<String, Component> componentsCache, Component component) {
523 Map<String, List<CapabilityDefinition>> capabilities = component.getCapabilities();
524 Either<Map<String, String[]>, ToscaError> res;
525 if (capabilities != null) {
526 res = buildAddSubstitutionMappingsCapabilities(componentsCache, component, capabilities);
528 res = Either.left(Maps.newHashMap());
529 logger.debug(NO_CAPABILITIES);
534 private String buildCapNamePerOwnerByPath(Map<String, Component> componentsCache, CapabilityDefinition c, Component component) {
535 return buildCapReqNamePerOwnerByPath(componentsCache, component, c.getName(), c.getPreviousName(), c.getPath());
538 private void convertProxyCapability(Map<String, ToscaCapability> toscaCapabilities, CapabilityDefinition c,
539 Map<String, DataTypeDefinition> dataTypes, String capabilityName) {
540 createToscaCapability(toscaCapabilities, c, dataTypes, capabilityName);
543 private void convertCapability(Map<String, Component> componentsCache, Component component, Map<String, ToscaCapability> toscaCapabilities, boolean isNodeType, CapabilityDefinition c, Map<String, DataTypeDefinition> dataTypes , String capabilityName) {
544 String name = isNoneBlank(capabilityName) ? capabilityName : c.getName();
545 if (!isNodeType && ToscaUtils.isNotComplexVfc(component)) {
546 name = buildCapNamePerOwnerByPath(componentsCache, c, component);
548 logger.debug("The capability {} belongs to resource {} ", name, component.getUniqueId());
549 createToscaCapability(toscaCapabilities, c, dataTypes, name);
552 private void createToscaCapability(Map<String, ToscaCapability> toscaCapabilities, CapabilityDefinition c,
553 Map<String, DataTypeDefinition> dataTypes, String name) {
554 ToscaCapability toscaCapability = new ToscaCapability();
555 toscaCapability.setDescription(c.getDescription());
556 toscaCapability.setType(c.getType());
558 List<Object> occurrences = new ArrayList<>();
559 occurrences.add(Integer.valueOf(c.getMinOccurrences()));
560 if (c.getMaxOccurrences().equals(CapabilityDataDefinition.MAX_OCCURRENCES)) {
561 occurrences.add(c.getMaxOccurrences());
563 occurrences.add(Integer.valueOf(c.getMaxOccurrences()));
565 toscaCapability.setOccurrences(occurrences);
567 toscaCapability.setValid_source_types(c.getValidSourceTypes());
568 List<ComponentInstanceProperty> properties = c.getProperties();
569 if (isNotEmpty(properties)) {
570 Map<String, ToscaProperty> toscaProperties = new HashMap<>();
571 for (PropertyDefinition property : properties) {
572 ToscaProperty toscaProperty = propertyConvertor.convertProperty(dataTypes, property, PropertyConvertor.PropertyType.CAPABILITY);
573 toscaProperties.put(property.getName(), toscaProperty);
575 toscaCapability.setProperties(toscaProperties);
577 toscaCapabilities.put(name, toscaCapability);
580 private String buildCapReqNamePerOwnerByPath(Map<String, Component> componentsCache, Component component, String name, String previousName, List<String> path) {
581 if (CollectionUtils.isEmpty(path)) {
584 String ownerId = path.get(path.size() - 1);
586 if(CollectionUtils.isNotEmpty(component.getGroups())) {
587 Optional<GroupDefinition> groupOpt = component.getGroups().stream().filter(g -> g.getUniqueId().equals(ownerId)).findFirst();
588 if (groupOpt.isPresent()) {
589 prefix = buildCapReqNamePrefix(groupOpt.get().getNormalizedName());
590 if(ComponentUtilities.isNotUpdatedCapReqName(prefix, name, previousName)){
591 return prefix + name;
596 Optional<ComponentInstance> ci = component.safeGetComponentInstances().stream().filter(c->c.getUniqueId().equals(Iterables.getLast(path))).findFirst();
598 logger.debug(FAILED_TO_FIND_CI_IN_PATH, path, component.getUniqueId());
600 Collections.reverse(path);
602 logger.debug("try to reverse path {} component {}", path, component.getUniqueId());
603 ci = component.safeGetComponentInstances().stream().filter(c->c.getUniqueId().equals(Iterables.getLast(path))).findFirst();
606 prefix = buildCapReqNamePrefix(ci.get().getNormalizedName());
607 if(ComponentUtilities.isNotUpdatedCapReqName(prefix, name, previousName)){
608 Either<String, Boolean> buildSubstitutedName = buildSubstitutedName(componentsCache, name, previousName, path, ownerId, ci.get());
609 if(buildSubstitutedName.isRight()){
610 logger.debug("Failed buildSubstitutedName name {} path {} component {}", name, path, component.getUniqueId());
612 return prefix + buildSubstitutedName.left().value();
616 return StringUtils.EMPTY;
619 * Allows to build substituted name of capability\requirement of the origin component instance according to the path
620 * @param componentsCache
621 * @param originComponent
624 * @param previousName
627 public Either<String, Boolean> buildSubstitutedName(Map<String, Component> componentsCache, Component originComponent, List<String> path, String name, String previousName) {
628 if(StringUtils.isNotEmpty(previousName)){
629 return Either.left(name);
631 StringBuilder substitutedName = new StringBuilder();
632 boolean nameBuiltSuccessfully = true;
633 if(isNotEmpty(path) && ToscaUtils.isNotComplexVfc(originComponent)){
634 List<String> reducedPath = getReducedPath(path);
635 Collections.reverse(reducedPath);
636 nameBuiltSuccessfully = appendNameRecursively(componentsCache, originComponent, reducedPath.iterator(), substitutedName);
638 return nameBuiltSuccessfully ? Either.left(substitutedName.append(name).toString()) : Either.right(nameBuiltSuccessfully);
641 protected List<String> getReducedPathByOwner(List<String> path , String ownerId) {
642 logger.debug("ownerId {}, path {} ", ownerId, path);
643 if ( CollectionUtils.isEmpty(path) ){
644 logger.debug("cannot perform reduce by owner, path to component is empty");
647 if ( isBlank(ownerId) ){
648 logger.debug("cannot perform reduce by owner, component owner is empty");
652 Map map = path.stream().collect( Collectors.toMap( it -> dropLast(it,PATH_DELIMITER) , Function.identity() , ( a , b ) -> a.endsWith(ownerId) ? a : b ));
653 //reduce list&duplicates and preserve order
654 return path.stream().distinct().filter(it -> map.values().contains(it) ).collect(Collectors.toList());
657 private List<String> getReducedPath(List<String> path) {
658 return path.stream().distinct().collect(Collectors.toList());
661 private boolean appendNameRecursively(Map<String, Component> componentsCache, Component originComponent, Iterator<String> instanceIdIter, StringBuilder substitutedName) {
662 if(isNotEmpty(originComponent.getComponentInstances()) && instanceIdIter.hasNext() && ToscaUtils.isNotComplexVfc(originComponent)){
663 String ownerId = instanceIdIter.next();
664 Optional<ComponentInstance> instanceOpt = originComponent.getComponentInstances().stream().filter(i -> i.getUniqueId().equals(ownerId)).findFirst();
665 if(instanceOpt.isPresent()){
666 substitutedName.append(instanceOpt.get().getNormalizedName()).append(PATH_DELIMITER);
667 Either<Component, Boolean> getOriginRes = getOriginComponent(componentsCache, instanceOpt.get());
668 if(getOriginRes.isRight()){
671 appendNameRecursively(componentsCache, getOriginRes.left().value(), instanceIdIter, substitutedName);
672 } else if(CollectionUtils.isNotEmpty(originComponent.getGroups())){
673 Optional<GroupDefinition> groupOpt = originComponent.getGroups().stream().filter(g -> g.getUniqueId().equals(ownerId)).findFirst();
674 if(!groupOpt.isPresent()){
675 logger.debug("Failed to find an capability owner with uniqueId {} on a component with uniqueId {}", ownerId, originComponent.getUniqueId());
678 substitutedName.append(groupOpt.get().getNormalizedName()).append(PATH_DELIMITER);
680 logger.debug("Failed to find an capability owner with uniqueId {} on a component with uniqueId {}", ownerId, originComponent.getUniqueId());
687 Either<Component, Boolean> getOriginComponent(Map<String, Component> componentsCache, ComponentInstance instance) {
688 Either<Component, Boolean> result;
689 Either<Component, StorageOperationStatus> getOriginRes;
690 if(componentsCache.containsKey(instance.getActualComponentUid())){
691 result = Either.left(componentsCache.get(instance.getActualComponentUid()));
693 ComponentParametersView filter = getFilter(instance);
694 getOriginRes = toscaOperationFacade.getToscaElement(instance.getActualComponentUid(), filter);
695 if(getOriginRes.isRight()){
696 logger.debug("Failed to get an origin component with uniqueId {}", instance.getActualComponentUid());
697 result = Either.right(false);
699 result = Either.left(getOriginRes.left().value());
700 componentsCache.put(getOriginRes.left().value().getUniqueId(), getOriginRes.left().value());
706 private ComponentParametersView getFilter(ComponentInstance instance) {
707 ComponentParametersView filter = new ComponentParametersView(true);
708 filter.setIgnoreComponentInstances(false);
709 if(instance.getIsProxy()){
710 filter.setIgnoreCapabilities(false);
711 filter.setIgnoreRequirements(false);
712 filter.setIgnoreCategories(false);
714 if(instance.getOriginType() == OriginTypeEnum.VF){
715 filter.setIgnoreGroups(false);