Remove dead code
[sdc.git] / catalog-be / src / main / java / org / openecomp / sdc / be / tosca / CapabilityRequirementConverter.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * SDC
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.openecomp.sdc.be.tosca;
22
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;
26
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;
35 import java.util.Map;
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;
70
71 /**
72  * Allows to convert requirements\capabilities of a component to requirements\capabilities of a substitution mappings section of a tosca template
73  *
74  */
75 @org.springframework.stereotype.Component("capabilty-requirement-convertor")
76 @Scope(value = "singleton")
77 public class CapabilityRequirementConverter {
78
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 {}";
85
86     @Autowired
87     private ToscaOperationFacade toscaOperationFacade;
88     @Autowired
89     private PropertyConvertor propertyConvertor;
90
91     public CapabilityRequirementConverter() {}
92
93     public static synchronized CapabilityRequirementConverter getInstance() {
94         if (instance == null) {
95             instance = new CapabilityRequirementConverter();
96         }
97         return instance;
98     }
99
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)
104                     .left()
105                     .orValue(c.getName());
106         }
107         return c.getPreviousName();
108     }
109
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());
118         }
119         return r.getPreviousName();
120     }
121
122     private String buildCapReqNamePrefix(String normalizedName) {
123         return normalizedName + PATH_DELIMITER;
124     }
125
126     /**
127      * Allows to convert capabilities of a component to capabilities of a substitution mappings section of a tosca template
128      * @param componentInstance
129      * @param dataTypes
130      * @param nodeTemplate
131      * @return
132      */
133     public Either<ToscaNodeTemplate, ToscaError> convertComponentInstanceCapabilities(ComponentInstance componentInstance, Map<String, DataTypeDefinition> dataTypes, ToscaNodeTemplate nodeTemplate) {
134
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() ) {
142                     capList.stream()
143                             .forEach( c -> convertOverridenProperties( componentInstance, dataTypes, capabilities, c ,
144                                 buildCapabilityNameForComponentInstance( componentCache , componentInstance , c )));
145                 }
146             });
147             if (MapUtils.isNotEmpty(capabilities)) {
148                 nodeTemplate.setCapabilities(capabilities);
149             }
150         }
151         return Either.left(nodeTemplate);
152     }
153
154     private void convertOverridenProperties(ComponentInstance componentInstance, Map<String, DataTypeDefinition> dataTypes, Map<String, ToscaTemplateCapability> capabilties, CapabilityDefinition c , String capabilityName) {
155         if (isNotEmpty(c.getProperties())) {
156             c.getProperties()
157             .stream()
158             .filter(p -> p.getValue() != null || p.getDefaultValue() != null)
159             .forEach(p -> convertOverriddenProperty(componentInstance, dataTypes, capabilties , p ,capabilityName));
160         }
161     }
162
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());
166         }
167         ToscaTemplateCapability toscaTemplateCapability = capabilties.computeIfAbsent( capabilityName , key -> new ToscaTemplateCapability() );
168
169         Map<String, Object> toscaCapProp = toscaTemplateCapability.getProperties();
170         if (toscaCapProp == null) {
171             toscaCapProp = new HashMap<>();
172         }
173         Object convertedValue = convertInstanceProperty(dataTypes, componentInstance, p);
174         toscaCapProp.put(p.getName(), convertedValue);
175         toscaTemplateCapability.setProperties(toscaCapProp);
176     }
177
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);
182     }
183     /**
184      * Allows to convert requirements of a node type to tosca template requirements representation
185      * @param component
186      * @param nodeType
187      * @return
188      */
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);
193         }
194         logger.debug("Finish convert Requirements for node type");
195
196         return Either.left(nodeType);
197     }
198
199     /**
200      * Allows to convert component requirements to the tosca template substitution mappings requirements
201      * @param componentsCache
202      * @param component
203      * @param substitutionMappings
204      * @return
205      */
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());
216         }
217         return result;
218     }
219
220     /**
221      * Allows to convert requirements of a server proxy node type to tosca template requirements
222      * @param instanceProxy
223      * @return converted tosca template requirements
224      */
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())
232                     .forEach(req -> {
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);
238             });
239         } else {
240             logger.debug(NO_REQUIREMENTS);
241         }
242
243         return toscaRequirements;
244     }
245
246     private ImmutablePair<String, ToscaRequirement> convertProxyRequirement(String requirementName,
247                                                                             RequirementDefinition r) {
248         ToscaRequirement toscaRequirement = createToscaRequirement(r);
249         return new ImmutablePair<>(requirementName, toscaRequirement);
250     }
251
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<>();
260
261                     requirement.put(pair.left, pair.right);
262                     toscaRequirements.add(requirement);
263                 });
264                 logger.debug("Finish convert Requirements for node type");
265             }
266         } else {
267             logger.debug(NO_REQUIREMENTS);
268         }
269         return toscaRequirements;
270     }
271
272     private boolean filter(Component component, String ownerId) {
273         return !ModelConverter.isAtomicComponent(component) || isNodeTypeOwner(component, ownerId) || (ModelConverter.isAtomicComponent(component) && ownerId == null);
274     }
275
276     private boolean isNodeTypeOwner(Component component, String ownerId) {
277         return ModelConverter.isAtomicComponent(component) && component.getUniqueId().equals(ownerId);
278     }
279
280     private String dropLast( String path, String delimiter ) {
281         if (isBlank(path) || isBlank(delimiter)){
282             return path;
283         }
284         return path.substring(0, path.lastIndexOf(delimiter));
285     }
286
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);
292         } else {
293             result = Either.left(Maps.newHashMap());
294             logger.debug("No requirements for substitution mappings section of a tosca template of the component {}. ", component.getName());
295         }
296         return result;
297     }
298
299     private Either<Map<String, String[]>, ToscaError> buildAddSubstitutionMappingsRequirements(Map<String, Component> componentsCache, Component component, Map<String, List<RequirementDefinition>> requirements) {
300
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()))
307                     .findAny();
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);
312             }
313             logger.debug("Finish convert requirements for the component {}. ", component.getName());
314         }
315         if(result == null){
316             result = Either.left(toscaRequirements);
317         }
318         return result;
319     }
320
321     private Either<Map<String, String[]>, ToscaError> buildAddSubstitutionMappingsCapabilities(Map<String, Component> componentsCache, Component component, Map<String, List<CapabilityDefinition>> capabilities) {
322
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()
327                     .stream()
328                     .filter(c->!addEntry(componentsCache, toscaCapabilities, component, new SubstitutionEntry(c.getName(), c.getParentName(), ""), c.getPreviousName(), c.getOwnerId(), c.getPath()))
329                     .findAny();
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);
334             }
335             logger.debug("Finish convert capabilities for the component {}. ", component.getName());
336         }
337         if(result == null){
338             result = Either.left(toscaCapabilities);
339         }
340         return result;
341     }
342
343     private boolean addEntry(Map<String, Component> componentsCache, Map<String, String[]> capReqMap, Component component, SubstitutionEntry entry, String previousName, String ownerId, List<String> path){
344     
345         if(shouldBuildSubstitutionName(component, path) && !buildSubstitutedNamePerInstance(componentsCache, component, entry.getFullName(), previousName, path, ownerId, entry)){
346             return false;
347         }
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);
351         }
352         logger.debug("Finish convert the requirement/capability {} for the component {}. ", entry.getFullName(), component.getName());
353         return true;
354
355     }
356
357     private boolean shouldBuildSubstitutionName(Component component, List<String> path) {
358         return ToscaUtils.isNotComplexVfc(component) && isNotEmpty(path) && path.iterator().hasNext();
359     }
360
361     private boolean buildSubstitutedNamePerInstance(Map<String, Component> componentsCache, Component component, String name, String previousName, List<String> path, String ownerId, SubstitutionEntry entry) {
362         String fullName;
363         String sourceName;
364         String prefix;
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)){
370                     sourceName = name;
371                     fullName = prefix + sourceName;
372                 } else {
373                     sourceName = previousName;
374                     fullName = name;
375                 }
376                 entry.setFullName(fullName);
377                 entry.setSourceName(sourceName);
378                 entry.setOwner(groupOpt.get().getNormalizedName());
379                 return true;
380             }
381         }
382
383         Optional<ComponentInstance> ci =
384                 component.safeGetComponentInstances().stream().filter(c->c.getUniqueId().equals(Iterables.getLast(path))).findFirst();
385         if(!ci.isPresent()){
386             logger.debug(FAILED_TO_FIND_CI_IN_PATH, path, component.getUniqueId());
387
388             Collections.reverse(path);
389
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();
392         }
393         if(ci.isPresent()){
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());
399                     return false;
400                 }
401                 sourceName = buildSubstitutedName.left().value();
402                 fullName = prefix + sourceName;
403             } else {
404                 sourceName = previousName;
405                 fullName = name;
406             }
407             entry.setFullName(fullName);
408             entry.setSourceName(sourceName);
409         } else {
410             logger.debug(FAILED_TO_FIND_CI_IN_PATH, path, component.getUniqueId());
411             return false;
412         }
413         return true;
414     }
415
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() });
421         }
422     }
423
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);
427         }
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);
432         }
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);
437     }
438
439     private String buildReqNamePerOwnerByPath(Map<String, Component> componentsCache, Component component, RequirementDefinition r) {
440         return buildCapReqNamePerOwnerByPath(componentsCache, component, r.getName(), r.getPreviousName(), r.getPath());
441     }
442
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);
447         }
448         logger.debug("the requirement {} belongs to resource {} ", name, component.getUniqueId());
449         ToscaRequirement toscaRequirement = createToscaRequirement(r);
450         return new ImmutablePair<>(name, toscaRequirement);
451     }
452
453     private ToscaRequirement createToscaRequirement(RequirementDefinition r) {
454         ToscaRequirement toscaRequirement = new ToscaRequirement();
455
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());
460         } else {
461             occurrences.add(Integer.valueOf(r.getMaxOccurrences()));
462         }
463         toscaRequirement.setOccurrences(occurrences);
464         toscaRequirement.setNode(r.getNode());
465         toscaRequirement.setCapability(r.getCapability());
466         toscaRequirement.setRelationship(r.getRelationship());
467         return toscaRequirement;
468     }
469
470     /**
471      * Allows to convert capabilities of a node type to tosca template capabilities
472      * @param component
473      * @param dataTypes
474      * @return
475      */
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()));
483             }
484         } else {
485             logger.debug(NO_CAPABILITIES);
486         }
487
488         return toscaCapabilities;
489     }
490
491     /**
492      * Allows to convert capabilities of a server proxy node type to tosca template capabilities
493      * @param instanceProxy
494      * @param dataTypes
495      * @return
496      */
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()) {
504                 entry.getValue()
505                         .stream()
506                         .forEach(c -> convertProxyCapability(toscaCapabilities, c, dataTypes ,
507                                 buildCapabilityNameForComponentInstance( componentCache , instanceProxy , c )));
508             }
509         } else {
510             logger.debug(NO_CAPABILITIES);
511         }
512
513         return toscaCapabilities;
514     }
515
516     /**
517      * Allows to convert component capabilities to the tosca template substitution mappings capabilities
518      * @param componentsCache
519      * @param component
520      * @return
521      */
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);
527         } else {
528             res = Either.left(Maps.newHashMap());
529             logger.debug(NO_CAPABILITIES);
530         }
531         return res;
532     }
533
534     private String buildCapNamePerOwnerByPath(Map<String, Component> componentsCache, CapabilityDefinition c, Component component) {
535         return buildCapReqNamePerOwnerByPath(componentsCache, component, c.getName(), c.getPreviousName(), c.getPath());
536     }
537
538     private void convertProxyCapability(Map<String, ToscaCapability> toscaCapabilities, CapabilityDefinition c,
539                                         Map<String, DataTypeDefinition> dataTypes, String capabilityName) {
540         createToscaCapability(toscaCapabilities, c, dataTypes, capabilityName);
541     }
542
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);
547         }
548         logger.debug("The capability {} belongs to resource {} ", name, component.getUniqueId());
549         createToscaCapability(toscaCapabilities, c, dataTypes, name);
550     }
551
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());
557
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());
562         } else {
563             occurrences.add(Integer.valueOf(c.getMaxOccurrences()));
564         }
565         toscaCapability.setOccurrences(occurrences);
566
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);
574             }
575             toscaCapability.setProperties(toscaProperties);
576         }
577         toscaCapabilities.put(name, toscaCapability);
578     }
579
580     private String buildCapReqNamePerOwnerByPath(Map<String, Component> componentsCache, Component component, String name, String previousName, List<String> path) {
581         if (CollectionUtils.isEmpty(path)) {
582             return name;
583         }
584         String ownerId = path.get(path.size() - 1);
585         String prefix;
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;
592                 }
593                 return name;
594             }
595         }
596         Optional<ComponentInstance> ci = component.safeGetComponentInstances().stream().filter(c->c.getUniqueId().equals(Iterables.getLast(path))).findFirst();
597         if(!ci.isPresent()){
598             logger.debug(FAILED_TO_FIND_CI_IN_PATH, path, component.getUniqueId());
599
600             Collections.reverse(path);
601
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();
604         }
605         if(ci.isPresent()){
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());
611                 }
612                 return prefix + buildSubstitutedName.left().value();
613             }
614             return name;
615         }
616         return StringUtils.EMPTY;
617     }
618     /**
619      * Allows to build substituted name of capability\requirement of the origin component instance according to the path
620      * @param componentsCache
621      * @param originComponent
622      * @param path
623      * @param name
624      * @param previousName
625      * @return
626      */
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);
630         }
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);
637         }
638         return nameBuiltSuccessfully ? Either.left(substitutedName.append(name).toString()) : Either.right(nameBuiltSuccessfully);
639     }
640
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");
645             return path;
646         }
647         if ( isBlank(ownerId) ){
648             logger.debug("cannot perform reduce by owner, component owner is empty");
649             return path;
650         }
651         //reduce by owner
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());
655     }
656
657     private List<String> getReducedPath(List<String> path) {
658         return path.stream().distinct().collect(Collectors.toList());
659     }
660
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()){
669                     return false;
670                 }
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());
676                     return false;
677                 }
678                 substitutedName.append(groupOpt.get().getNormalizedName()).append(PATH_DELIMITER);
679             } else {
680                 logger.debug("Failed to find an capability owner with uniqueId {} on a component with uniqueId {}", ownerId, originComponent.getUniqueId());
681                 return false;
682             }
683         }
684         return true;
685     }
686
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()));
692         } else {
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);
698             } else {
699                 result = Either.left(getOriginRes.left().value());
700                 componentsCache.put(getOriginRes.left().value().getUniqueId(), getOriginRes.left().value());
701             }
702         }
703         return result;
704     }
705
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);
713         }
714         if(instance.getOriginType() == OriginTypeEnum.VF){
715             filter.setIgnoreGroups(false);
716         }
717         return filter;
718     }
719
720 }