88f3666305d6e4c3efd556ad142fbf4b63885a14
[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 package org.openecomp.sdc.be.tosca;
21
22 import static org.apache.commons.collections.CollectionUtils.isNotEmpty;
23 import static org.apache.commons.lang3.StringUtils.isBlank;
24 import static org.apache.commons.lang3.StringUtils.isNoneBlank;
25
26 import com.google.common.collect.Iterables;
27 import com.google.common.collect.Maps;
28 import fj.data.Either;
29 import java.util.ArrayList;
30 import java.util.Collections;
31 import java.util.HashMap;
32 import java.util.Iterator;
33 import java.util.List;
34 import java.util.Map;
35 import java.util.Optional;
36 import java.util.function.Function;
37 import java.util.stream.Collectors;
38 import org.apache.commons.collections.CollectionUtils;
39 import org.apache.commons.collections.MapUtils;
40 import org.apache.commons.lang3.StringUtils;
41 import org.apache.commons.lang3.tuple.ImmutablePair;
42 import org.openecomp.sdc.be.datatypes.elements.CapabilityDataDefinition;
43 import org.openecomp.sdc.be.datatypes.elements.RequirementDataDefinition;
44 import org.openecomp.sdc.be.datatypes.enums.OriginTypeEnum;
45 import org.openecomp.sdc.be.model.CapabilityDefinition;
46 import org.openecomp.sdc.be.model.Component;
47 import org.openecomp.sdc.be.model.ComponentInstance;
48 import org.openecomp.sdc.be.model.ComponentInstanceProperty;
49 import org.openecomp.sdc.be.model.ComponentParametersView;
50 import org.openecomp.sdc.be.model.DataTypeDefinition;
51 import org.openecomp.sdc.be.model.GroupDefinition;
52 import org.openecomp.sdc.be.model.PropertyDefinition;
53 import org.openecomp.sdc.be.model.RequirementDefinition;
54 import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade;
55 import org.openecomp.sdc.be.model.jsonjanusgraph.utils.ModelConverter;
56 import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
57 import org.openecomp.sdc.be.model.utils.ComponentUtilities;
58 import org.openecomp.sdc.be.tosca.ToscaUtils.SubstitutionEntry;
59 import org.openecomp.sdc.be.tosca.model.SubstitutionMapping;
60 import org.openecomp.sdc.be.tosca.model.ToscaCapability;
61 import org.openecomp.sdc.be.tosca.model.ToscaNodeTemplate;
62 import org.openecomp.sdc.be.tosca.model.ToscaNodeType;
63 import org.openecomp.sdc.be.tosca.model.ToscaProperty;
64 import org.openecomp.sdc.be.tosca.model.ToscaRequirement;
65 import org.openecomp.sdc.be.tosca.model.ToscaTemplateCapability;
66 import org.openecomp.sdc.common.log.wrappers.Logger;
67 import org.springframework.beans.factory.annotation.Autowired;
68 import org.springframework.context.annotation.Scope;
69
70 /**
71  * Allows to convert requirements\capabilities of a component to requirements\capabilities of a substitution mappings section of a tosca template
72  */
73 @org.springframework.stereotype.Component("capabilty-requirement-convertor")
74 @Scope(value = "singleton")
75 public class CapabilityRequirementConverter {
76
77     private static final String NO_CAPABILITIES = "No Capabilities for node type";
78     private static final String NO_REQUIREMENTS = "No Requirements for node type";
79     private static final Logger logger = Logger.getLogger(CapabilityRequirementConverter.class);
80     private static final String PATH_DELIMITER = ".";
81     private static final String FAILED_TO_FIND_CI_IN_PATH = "Failed to find ci in the path is {} component {}";
82     private static CapabilityRequirementConverter instance;
83     @Autowired
84     private ToscaOperationFacade toscaOperationFacade;
85     @Autowired
86     private PropertyConvertor propertyConvertor;
87
88     public CapabilityRequirementConverter() {
89     }
90
91     public static synchronized CapabilityRequirementConverter getInstance() {
92         if (instance == null) {
93             instance = new CapabilityRequirementConverter();
94         }
95         return instance;
96     }
97
98     public String buildCapabilityNameForComponentInstance(Map<String, Component> componentCache, ComponentInstance componentInstance,
99                                                           CapabilityDefinition c) {
100         String prefix = buildCapReqNamePrefix(componentInstance.getNormalizedName());
101         if (ComponentUtilities.isNotUpdatedCapReqName(prefix, c.getName(), c.getPreviousName())) {
102             return buildSubstitutedName(componentCache, c.getName(), c.getPreviousName(), c.getPath(), c.getOwnerId(), componentInstance).left()
103                 .orValue(c.getName());
104         }
105         return c.getPreviousName();
106     }
107
108     public String buildRequirementNameForComponentInstance(Map<String, Component> componentCache, ComponentInstance componentInstance,
109                                                            RequirementDefinition r) {
110         String prefix = buildCapReqNamePrefix(componentInstance.getNormalizedName());
111         if (ComponentUtilities.isNotUpdatedCapReqName(prefix, r.getName(), r.getPreviousName())) {
112             return buildSubstitutedName(componentCache, r.getName(), r.getPreviousName(), r.getPath(), r.getOwnerId(), componentInstance).left()
113                 .orValue(r.getName());
114         }
115         return r.getPreviousName();
116     }
117
118     private String buildCapReqNamePrefix(String normalizedName) {
119         return normalizedName + PATH_DELIMITER;
120     }
121
122     /**
123      * Allows to convert capabilities of a component to capabilities of a substitution mappings section of a tosca template
124      *
125      * @param componentInstance
126      * @param dataTypes
127      * @param nodeTemplate
128      * @return
129      */
130     public Either<ToscaNodeTemplate, ToscaError> convertComponentInstanceCapabilities(ComponentInstance componentInstance,
131                                                                                       Map<String, DataTypeDefinition> dataTypes,
132                                                                                       ToscaNodeTemplate nodeTemplate) {
133         Map<String, List<CapabilityDefinition>> capabilitiesInst = componentInstance.getCapabilities();
134         Map<String, Component> componentCache = new HashMap<>();
135         if (capabilitiesInst != null && !capabilitiesInst.isEmpty()) {
136             Map<String, ToscaTemplateCapability> capabilities = new HashMap<>();
137             capabilitiesInst.entrySet().forEach(e -> {
138                 List<CapabilityDefinition> capList = e.getValue();
139                 if (capList != null && !capList.isEmpty()) {
140                     capList.stream().forEach(c -> convertOverridenProperties(componentInstance, dataTypes, capabilities, c,
141                         buildCapabilityNameForComponentInstance(componentCache, componentInstance, c)));
142                 }
143             });
144             if (MapUtils.isNotEmpty(capabilities)) {
145                 nodeTemplate.setCapabilities(capabilities);
146             }
147         }
148         return Either.left(nodeTemplate);
149     }
150
151     private void convertOverridenProperties(ComponentInstance componentInstance, Map<String, DataTypeDefinition> dataTypes,
152                                             Map<String, ToscaTemplateCapability> capabilties, CapabilityDefinition c, String capabilityName) {
153         if (isNotEmpty(c.getProperties())) {
154             c.getProperties().stream().filter(p -> p.getValue() != null || p.getDefaultValue() != null)
155                 .forEach(p -> convertOverriddenProperty(componentInstance, dataTypes, capabilties, p, capabilityName));
156         }
157     }
158
159     private void convertOverriddenProperty(ComponentInstance componentInstance, Map<String, DataTypeDefinition> dataTypes,
160                                            Map<String, ToscaTemplateCapability> capabilties, ComponentInstanceProperty p, String capabilityName) {
161         if (logger.isDebugEnabled()) {
162             logger.debug("Exist d property {} for capability {} with value {}", p.getName(), capabilityName, p.getValue());
163         }
164         ToscaTemplateCapability toscaTemplateCapability = capabilties.computeIfAbsent(capabilityName, key -> new ToscaTemplateCapability());
165         Map<String, Object> toscaCapProp = toscaTemplateCapability.getProperties();
166         if (toscaCapProp == null) {
167             toscaCapProp = new HashMap<>();
168         }
169         Object convertedValue = convertInstanceProperty(dataTypes, componentInstance, p);
170         toscaCapProp.put(p.getName(), convertedValue);
171         toscaTemplateCapability.setProperties(toscaCapProp);
172     }
173
174     private Object convertInstanceProperty(Map<String, DataTypeDefinition> dataTypes, ComponentInstance componentInstance,
175                                            ComponentInstanceProperty prop) {
176         logger.debug("Convert property {} for instance {}", prop.getName(), componentInstance.getUniqueId());
177         String propValue = prop.getValue() == null ? prop.getDefaultValue() : prop.getValue();
178         return propertyConvertor.convertToToscaObject(prop, propValue, dataTypes, false);
179     }
180
181     /**
182      * Allows to convert requirements of a node type to tosca template requirements representation
183      *
184      * @param component
185      * @param nodeType
186      * @return
187      */
188     public Either<ToscaNodeType, ToscaError> convertRequirements(Map<String, Component> componentsCache, Component component,
189                                                                  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         return Either.left(nodeType);
196     }
197
198     /**
199      * Allows to convert component requirements to the tosca template substitution mappings requirements
200      *
201      * @param componentsCache
202      * @param component
203      * @param substitutionMappings
204      * @return
205      */
206     public Either<SubstitutionMapping, ToscaError> convertSubstitutionMappingRequirements(Map<String, Component> componentsCache, Component component,
207                                                                                           SubstitutionMapping substitutionMappings) {
208         Either<SubstitutionMapping, ToscaError> result = Either.left(substitutionMappings);
209         Either<Map<String, String[]>, ToscaError> toscaRequirementsRes = convertSubstitutionMappingRequirementsAsMap(componentsCache, component);
210         if (toscaRequirementsRes.isRight()) {
211             result = Either.right(toscaRequirementsRes.right().value());
212             logger.debug("Failed convert requirements for the component {}. ", component.getName());
213         } else if (MapUtils.isNotEmpty(toscaRequirementsRes.left().value())) {
214             substitutionMappings.setRequirements(toscaRequirementsRes.left().value());
215             result = Either.left(substitutionMappings);
216             logger.debug("Finish convert requirements for the component {}. ", component.getName());
217         }
218         return result;
219     }
220
221     /**
222      * Allows to convert requirements of a server proxy node type to tosca template requirements
223      *
224      * @param instanceProxy
225      * @return converted tosca template requirements
226      */
227     List<Map<String, ToscaRequirement>> convertProxyRequirements(Map<String, Component> componentCache, ComponentInstance instanceProxy) {
228         Map<String, List<RequirementDefinition>> requirements = instanceProxy.getRequirements();
229         List<Map<String, ToscaRequirement>> toscaRequirements = new ArrayList<>();
230         if (requirements != null) {
231             requirements.entrySet().stream().flatMap(e -> e.getValue().stream()).forEach(req -> {
232                 ImmutablePair<String, ToscaRequirement> pair = convertProxyRequirement(
233                     buildRequirementNameForComponentInstance(componentCache, instanceProxy, req), req);
234                 Map<String, ToscaRequirement> requirement = new HashMap<>();
235                 requirement.put(pair.left, pair.right);
236                 toscaRequirements.add(requirement);
237             });
238         } else {
239             logger.debug(NO_REQUIREMENTS);
240         }
241         return toscaRequirements;
242     }
243
244     private ImmutablePair<String, ToscaRequirement> convertProxyRequirement(String requirementName, RequirementDefinition r) {
245         ToscaRequirement toscaRequirement = createToscaRequirement(r);
246         return new ImmutablePair<>(requirementName, toscaRequirement);
247     }
248
249     private List<Map<String, ToscaRequirement>> convertRequirementsAsList(Map<String, Component> componentsCache, Component component) {
250         Map<String, List<RequirementDefinition>> requirements = component.getRequirements();
251         List<Map<String, ToscaRequirement>> toscaRequirements = new ArrayList<>();
252         if (requirements != null) {
253             for (Map.Entry<String, List<RequirementDefinition>> entry : requirements.entrySet()) {
254                 entry.getValue().stream().filter(r -> filter(component, r.getOwnerId())).forEach(r -> {
255                     ImmutablePair<String, ToscaRequirement> pair = convertRequirement(componentsCache, component,
256                         ModelConverter.isAtomicComponent(component), r);
257                     Map<String, ToscaRequirement> requirement = new HashMap<>();
258                     requirement.put(pair.left, pair.right);
259                     toscaRequirements.add(requirement);
260                 });
261                 logger.debug("Finish convert Requirements for node type");
262             }
263         } else {
264             logger.debug(NO_REQUIREMENTS);
265         }
266         return toscaRequirements;
267     }
268
269     private boolean filter(Component component, String ownerId) {
270         return !ModelConverter.isAtomicComponent(component) || isNodeTypeOwner(component, ownerId) || (ModelConverter.isAtomicComponent(component)
271             && ownerId == null);
272     }
273
274     private boolean isNodeTypeOwner(Component component, String ownerId) {
275         return ModelConverter.isAtomicComponent(component) && component.getUniqueId().equals(ownerId);
276     }
277
278     private String dropLast(String path, String delimiter) {
279         if (isBlank(path) || isBlank(delimiter)) {
280             return path;
281         }
282         return path.substring(0, path.lastIndexOf(delimiter));
283     }
284
285     private Either<Map<String, String[]>, ToscaError> convertSubstitutionMappingRequirementsAsMap(Map<String, Component> componentsCache,
286                                                                                                   Component component) {
287         Map<String, List<RequirementDefinition>> requirements = component.getRequirements();
288         Either<Map<String, String[]>, ToscaError> result;
289         if (requirements != null) {
290             result = buildAddSubstitutionMappingsRequirements(componentsCache, component, requirements);
291         } else {
292             result = Either.left(Maps.newHashMap());
293             logger.debug("No requirements for substitution mappings section of a tosca template of the component {}. ", component.getName());
294         }
295         return result;
296     }
297
298     private Either<Map<String, String[]>, ToscaError> buildAddSubstitutionMappingsRequirements(Map<String, Component> componentsCache,
299                                                                                                Component component,
300                                                                                                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().stream().filter(RequirementDefinition::isExternal).filter(
305                 r -> !addEntry(componentsCache, toscaRequirements, component, new SubstitutionEntry(r.getName(), r.getParentName(), ""),
306                     r.getPreviousName(), r.getOwnerId(), r.getPath())).findAny();
307             if (failedToAddRequirement.isPresent()) {
308                 logger.debug("Failed to convert requirement {} for substitution mappings section of a tosca template of the component {}. ",
309                     failedToAddRequirement.get().getName(), component.getName());
310                 result = Either.right(ToscaError.NODE_TYPE_REQUIREMENT_ERROR);
311             }
312             logger.debug("Finish convert requirements for the component {}. ", component.getName());
313         }
314         if (result == null) {
315             result = Either.left(toscaRequirements);
316         }
317         return result;
318     }
319
320     private Either<Map<String, String[]>, ToscaError> buildAddSubstitutionMappingsCapabilities(Map<String, Component> componentsCache,
321                                                                                                Component component,
322                                                                                                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().stream()
327                 .filter(CapabilityDataDefinition::isExternal)
328                 .filter( c -> !addEntry(componentsCache, toscaCapabilities, component, new SubstitutionEntry(c.getName(), c.getParentName(), "")
329                     , c.getPreviousName(), c.getOwnerId(), c.getPath()))
330                 .findAny();
331             if (failedToAddRequirement.isPresent()) {
332                 logger.debug("Failed to convert capability {} for substitution mappings section of a tosca template of the component {}. ",
333                     failedToAddRequirement.get().getName(), component.getName());
334                 result = Either.right(ToscaError.NODE_TYPE_CAPABILITY_ERROR);
335             }
336             logger.debug("Finish convert capabilities for the component {}. ", component.getName());
337         }
338         if (result == null) {
339             result = Either.left(toscaCapabilities);
340         }
341         return result;
342     }
343
344     private boolean addEntry(Map<String, Component> componentsCache, Map<String, String[]> capReqMap, Component component, SubstitutionEntry entry,
345                              String previousName, String ownerId, List<String> path) {
346         if (shouldBuildSubstitutionName(component, path) && !buildSubstitutedNamePerInstance(componentsCache, component, entry.getFullName(),
347             previousName, path, ownerId, entry)) {
348             return false;
349         }
350         logger.debug("The requirement/capability {} belongs to the component {} ", entry.getFullName(), component.getUniqueId());
351         if (StringUtils.isNotEmpty(entry.getSourceName())) {
352             addEntry(capReqMap, component, path, entry);
353         }
354         logger.debug("Finish convert the requirement/capability {} for the component {}. ", entry.getFullName(), component.getName());
355         return true;
356     }
357
358     private boolean shouldBuildSubstitutionName(Component component, List<String> path) {
359         return ToscaUtils.isNotComplexVfc(component) && isNotEmpty(path) && path.iterator().hasNext();
360     }
361
362     private boolean buildSubstitutedNamePerInstance(Map<String, Component> componentsCache, Component component, String name, String previousName,
363                                                     List<String> path, String ownerId, SubstitutionEntry entry) {
364         String fullName;
365         String sourceName;
366         String prefix;
367         if (CollectionUtils.isNotEmpty(component.getGroups())) {
368             Optional<GroupDefinition> groupOpt = component.getGroups().stream().filter(g -> g.getUniqueId().equals(ownerId)).findFirst();
369             if (groupOpt.isPresent()) {
370                 prefix = buildCapReqNamePrefix(groupOpt.get().getNormalizedName());
371                 if (ComponentUtilities.isNotUpdatedCapReqName(prefix, name, previousName)) {
372                     sourceName = name;
373                     fullName = prefix + sourceName;
374                 } else {
375                     sourceName = previousName;
376                     fullName = name;
377                 }
378                 entry.setFullName(fullName);
379                 entry.setSourceName(sourceName);
380                 entry.setOwner(groupOpt.get().getNormalizedName());
381                 return true;
382             }
383         }
384         Optional<ComponentInstance> ci = component.safeGetComponentInstances().stream().filter(c -> c.getUniqueId().equals(Iterables.getLast(path)))
385             .findFirst();
386         if (!ci.isPresent()) {
387             logger.debug(FAILED_TO_FIND_CI_IN_PATH, path, component.getUniqueId());
388             Collections.reverse(path);
389             logger.debug("try to reverse path {} component {}", path, component.getUniqueId());
390             ci = component.safeGetComponentInstances().stream().filter(c -> c.getUniqueId().equals(Iterables.getLast(path))).findFirst();
391         }
392         if (ci.isPresent()) {
393             prefix = buildCapReqNamePrefix(ci.get().getNormalizedName());
394             if (ComponentUtilities.isNotUpdatedCapReqName(prefix, name, previousName)) {
395                 Either<String, Boolean> buildSubstitutedName = buildSubstitutedName(componentsCache, name, previousName, path, ownerId, ci.get());
396                 if (buildSubstitutedName.isRight()) {
397                     logger.debug("Failed buildSubstitutedName name {}  path {} component {}", name, path, component.getUniqueId());
398                     return false;
399                 }
400                 sourceName = buildSubstitutedName.left().value();
401                 fullName = prefix + sourceName;
402             } else {
403                 sourceName = previousName;
404                 fullName = name;
405             }
406             entry.setFullName(fullName);
407             entry.setSourceName(sourceName);
408         } else {
409             logger.debug(FAILED_TO_FIND_CI_IN_PATH, path, component.getUniqueId());
410             return false;
411         }
412         return true;
413     }
414
415     private void addEntry(Map<String, String[]> toscaRequirements, Component component, List<String> capPath, SubstitutionEntry entry) {
416         Optional<ComponentInstance> findFirst = component.safeGetComponentInstances().stream()
417             .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,
425                                                         String ownerId, ComponentInstance instance) {
426         if (StringUtils.isNotEmpty(previousName)) {
427             return Either.left(name);
428         }
429         Either<Component, Boolean> getOriginRes = getOriginComponent(componentsCache, instance);
430         if (getOriginRes.isRight()) {
431             logger
432                 .debug("Failed to build substituted name for the capability/requirement {}. Failed to get an origin component with uniqueId {}", name,
433                     instance.getComponentUid());
434             return Either.right(false);
435         }
436         List<String> reducedPath = ownerId != null ? getReducedPathByOwner(path, ownerId) : getReducedPath(path);
437         logger.debug("reducedPath for ownerId {}, reducedPath {} ", ownerId, reducedPath);
438         reducedPath.remove(reducedPath.size() - 1);
439         return buildSubstitutedName(componentsCache, getOriginRes.left().value(), reducedPath, name, previousName);
440     }
441
442     private String buildReqNamePerOwnerByPath(Map<String, Component> componentsCache, Component component, RequirementDefinition r) {
443         return buildCapReqNamePerOwnerByPath(componentsCache, component, r.getName(), r.getPreviousName(), r.getPath());
444     }
445
446     private ImmutablePair<String, ToscaRequirement> convertRequirement(Map<String, Component> componentsCache, Component component,
447                                                                        boolean isNodeType, RequirementDefinition r) {
448         String name = r.getName();
449         if (!isNodeType && ToscaUtils.isNotComplexVfc(component)) {
450             name = buildReqNamePerOwnerByPath(componentsCache, component, r);
451         }
452         logger.debug("the requirement {} belongs to resource {} ", name, component.getUniqueId());
453         ToscaRequirement toscaRequirement = createToscaRequirement(r);
454         return new ImmutablePair<>(name, toscaRequirement);
455     }
456
457     private ToscaRequirement createToscaRequirement(RequirementDefinition r) {
458         ToscaRequirement toscaRequirement = new ToscaRequirement();
459         List<Object> occurrences = new ArrayList<>();
460         occurrences.add(Integer.valueOf(r.getMinOccurrences()));
461         if (r.getMaxOccurrences().equals(RequirementDataDefinition.MAX_OCCURRENCES)) {
462             occurrences.add(r.getMaxOccurrences());
463         } else {
464             occurrences.add(Integer.valueOf(r.getMaxOccurrences()));
465         }
466         toscaRequirement.setOccurrences(occurrences);
467         toscaRequirement.setNode(r.getNode());
468         toscaRequirement.setCapability(r.getCapability());
469         toscaRequirement.setRelationship(r.getRelationship());
470         return toscaRequirement;
471     }
472
473     /**
474      * Allows to convert capabilities of a node type to tosca template capabilities
475      *
476      * @param component
477      * @param dataTypes
478      * @return
479      */
480     public Map<String, ToscaCapability> convertCapabilities(Map<String, Component> componentsCache, Component component,
481                                                             Map<String, DataTypeDefinition> dataTypes) {
482         Map<String, List<CapabilityDefinition>> capabilities = component.getCapabilities();
483         Map<String, ToscaCapability> toscaCapabilities = new HashMap<>();
484         if (capabilities != null) {
485             boolean isNodeType = ModelConverter.isAtomicComponent(component);
486             for (Map.Entry<String, List<CapabilityDefinition>> entry : capabilities.entrySet()) {
487                 entry.getValue().stream().filter(c -> filter(component, c.getOwnerId()))
488                     .forEach(c -> convertCapability(componentsCache, component, toscaCapabilities, isNodeType, c, dataTypes, c.getName()));
489             }
490         } else {
491             logger.debug(NO_CAPABILITIES);
492         }
493         return toscaCapabilities;
494     }
495
496     /**
497      * Allows to convert capabilities of a server proxy node type to tosca template capabilities
498      *
499      * @param instanceProxy
500      * @param dataTypes
501      * @return
502      */
503     public Map<String, ToscaCapability> convertProxyCapabilities(Map<String, Component> componentCache, ComponentInstance instanceProxy,
504                                                                  Map<String, DataTypeDefinition> dataTypes) {
505         Map<String, List<CapabilityDefinition>> capabilities = instanceProxy.getCapabilities();
506         Map<String, ToscaCapability> toscaCapabilities = new HashMap<>();
507         if (capabilities != null) {
508             for (Map.Entry<String, List<CapabilityDefinition>> entry : capabilities.entrySet()) {
509                 entry.getValue().stream().forEach(c -> convertProxyCapability(toscaCapabilities, c, dataTypes,
510                     buildCapabilityNameForComponentInstance(componentCache, instanceProxy, c)));
511             }
512         } else {
513             logger.debug(NO_CAPABILITIES);
514         }
515         return toscaCapabilities;
516     }
517
518     /**
519      * Allows to convert component capabilities to the tosca template substitution mappings capabilities
520      *
521      * @param componentsCache
522      * @param component
523      * @return
524      */
525     public Either<Map<String, String[]>, ToscaError> convertSubstitutionMappingCapabilities(Map<String, Component> componentsCache,
526                                                                                             Component component) {
527         Map<String, List<CapabilityDefinition>> capabilities = component.getCapabilities();
528         Either<Map<String, String[]>, ToscaError> res;
529         if (capabilities != null) {
530             res = buildAddSubstitutionMappingsCapabilities(componentsCache, component, capabilities);
531         } else {
532             res = Either.left(Maps.newHashMap());
533             logger.debug(NO_CAPABILITIES);
534         }
535         return res;
536     }
537
538     private String buildCapNamePerOwnerByPath(Map<String, Component> componentsCache, CapabilityDefinition c, Component component) {
539         return buildCapReqNamePerOwnerByPath(componentsCache, component, c.getName(), c.getPreviousName(), c.getPath());
540     }
541
542     private void convertProxyCapability(Map<String, ToscaCapability> toscaCapabilities, CapabilityDefinition c,
543                                         Map<String, DataTypeDefinition> dataTypes, String capabilityName) {
544         createToscaCapability(toscaCapabilities, c, dataTypes, capabilityName);
545     }
546
547     private void convertCapability(Map<String, Component> componentsCache, Component component, Map<String, ToscaCapability> toscaCapabilities,
548                                    boolean isNodeType, CapabilityDefinition c, Map<String, DataTypeDefinition> dataTypes, String capabilityName) {
549         String name = isNoneBlank(capabilityName) ? capabilityName : c.getName();
550         if (!isNodeType && ToscaUtils.isNotComplexVfc(component)) {
551             name = buildCapNamePerOwnerByPath(componentsCache, c, component);
552         }
553         logger.debug("The capability {} belongs to resource {} ", name, component.getUniqueId());
554         createToscaCapability(toscaCapabilities, c, dataTypes, name);
555     }
556
557     private void createToscaCapability(Map<String, ToscaCapability> toscaCapabilities, CapabilityDefinition c,
558                                        Map<String, DataTypeDefinition> dataTypes, String name) {
559         ToscaCapability toscaCapability = new ToscaCapability();
560         toscaCapability.setDescription(c.getDescription());
561         toscaCapability.setType(c.getType());
562         List<Object> occurrences = new ArrayList<>();
563         occurrences.add(Integer.valueOf(c.getMinOccurrences()));
564         if (c.getMaxOccurrences().equals(CapabilityDataDefinition.MAX_OCCURRENCES)) {
565             occurrences.add(c.getMaxOccurrences());
566         } else {
567             occurrences.add(Integer.valueOf(c.getMaxOccurrences()));
568         }
569         toscaCapability.setOccurrences(occurrences);
570         toscaCapability.setValid_source_types(c.getValidSourceTypes());
571         List<ComponentInstanceProperty> properties = c.getProperties();
572         if (isNotEmpty(properties)) {
573             Map<String, ToscaProperty> toscaProperties = new HashMap<>();
574             for (PropertyDefinition property : properties) {
575                 ToscaProperty toscaProperty = propertyConvertor.convertProperty(dataTypes, property, PropertyConvertor.PropertyType.CAPABILITY);
576                 toscaProperties.put(property.getName(), toscaProperty);
577             }
578             toscaCapability.setProperties(toscaProperties);
579         }
580         toscaCapabilities.put(name, toscaCapability);
581     }
582
583     private String buildCapReqNamePerOwnerByPath(Map<String, Component> componentsCache, Component component, String name, String previousName,
584                                                  List<String> path) {
585         if (CollectionUtils.isEmpty(path)) {
586             return name;
587         }
588         String ownerId = path.get(path.size() - 1);
589         String prefix;
590         if (CollectionUtils.isNotEmpty(component.getGroups())) {
591             Optional<GroupDefinition> groupOpt = component.getGroups().stream().filter(g -> g.getUniqueId().equals(ownerId)).findFirst();
592             if (groupOpt.isPresent()) {
593                 prefix = buildCapReqNamePrefix(groupOpt.get().getNormalizedName());
594                 if (ComponentUtilities.isNotUpdatedCapReqName(prefix, name, previousName)) {
595                     return prefix + name;
596                 }
597                 return name;
598             }
599         }
600         Optional<ComponentInstance> ci = component.safeGetComponentInstances().stream().filter(c -> c.getUniqueId().equals(Iterables.getLast(path)))
601             .findFirst();
602         if (!ci.isPresent()) {
603             logger.debug(FAILED_TO_FIND_CI_IN_PATH, path, component.getUniqueId());
604             Collections.reverse(path);
605             logger.debug("try to reverse path {} component {}", path, component.getUniqueId());
606             ci = component.safeGetComponentInstances().stream().filter(c -> c.getUniqueId().equals(Iterables.getLast(path))).findFirst();
607         }
608         if (ci.isPresent()) {
609             prefix = buildCapReqNamePrefix(ci.get().getNormalizedName());
610             if (ComponentUtilities.isNotUpdatedCapReqName(prefix, name, previousName)) {
611                 Either<String, Boolean> buildSubstitutedName = buildSubstitutedName(componentsCache, name, previousName, path, ownerId, ci.get());
612                 if (buildSubstitutedName.isRight()) {
613                     logger.debug("Failed buildSubstitutedName name {}  path {} component {}", name, path, component.getUniqueId());
614                 }
615                 return prefix + buildSubstitutedName.left().value();
616             }
617             return name;
618         }
619         return StringUtils.EMPTY;
620     }
621
622     /**
623      * Allows to build substituted name of capability\requirement of the origin component instance according to the path
624      *
625      * @param componentsCache
626      * @param originComponent
627      * @param path
628      * @param name
629      * @param previousName
630      * @return
631      */
632     public Either<String, Boolean> buildSubstitutedName(Map<String, Component> componentsCache, Component originComponent, List<String> path,
633                                                         String name, String previousName) {
634         if (StringUtils.isNotEmpty(previousName)) {
635             return Either.left(name);
636         }
637         StringBuilder substitutedName = new StringBuilder();
638         boolean nameBuiltSuccessfully = true;
639         if (isNotEmpty(path) && ToscaUtils.isNotComplexVfc(originComponent)) {
640             List<String> reducedPath = getReducedPath(path);
641             Collections.reverse(reducedPath);
642             nameBuiltSuccessfully = appendNameRecursively(componentsCache, originComponent, reducedPath.iterator(), substitutedName);
643         }
644         return nameBuiltSuccessfully ? Either.left(substitutedName.append(name).toString()) : Either.right(nameBuiltSuccessfully);
645     }
646
647     protected List<String> getReducedPathByOwner(List<String> path, String ownerId) {
648         logger.debug("ownerId {}, path {} ", ownerId, path);
649         if (CollectionUtils.isEmpty(path)) {
650             logger.debug("cannot perform reduce by owner, path to component is empty");
651             return path;
652         }
653         if (isBlank(ownerId)) {
654             logger.debug("cannot perform reduce by owner, component owner is empty");
655             return path;
656         }
657         //reduce by owner
658         Map map = path.stream()
659             .collect(Collectors.toMap(it -> dropLast(it, PATH_DELIMITER), Function.identity(), (a, b) -> a.endsWith(ownerId) ? a : b));
660         //reduce list&duplicates and preserve order
661         return path.stream().distinct().filter(it -> map.values().contains(it)).collect(Collectors.toList());
662     }
663
664     private List<String> getReducedPath(List<String> path) {
665         return path.stream().distinct().collect(Collectors.toList());
666     }
667
668     private boolean appendNameRecursively(Map<String, Component> componentsCache, Component originComponent, Iterator<String> instanceIdIter,
669                                           StringBuilder substitutedName) {
670         if (isNotEmpty(originComponent.getComponentInstances()) && instanceIdIter.hasNext() && ToscaUtils.isNotComplexVfc(originComponent)) {
671             String ownerId = instanceIdIter.next();
672             Optional<ComponentInstance> instanceOpt = originComponent.getComponentInstances().stream().filter(i -> i.getUniqueId().equals(ownerId))
673                 .findFirst();
674             if (instanceOpt.isPresent()) {
675                 substitutedName.append(instanceOpt.get().getNormalizedName()).append(PATH_DELIMITER);
676                 Either<Component, Boolean> getOriginRes = getOriginComponent(componentsCache, instanceOpt.get());
677                 if (getOriginRes.isRight()) {
678                     return false;
679                 }
680                 appendNameRecursively(componentsCache, getOriginRes.left().value(), instanceIdIter, substitutedName);
681             } else if (CollectionUtils.isNotEmpty(originComponent.getGroups())) {
682                 Optional<GroupDefinition> groupOpt = originComponent.getGroups().stream().filter(g -> g.getUniqueId().equals(ownerId)).findFirst();
683                 if (!groupOpt.isPresent()) {
684                     logger.debug("Failed to find an capability owner with uniqueId {} on a component with uniqueId {}", ownerId,
685                         originComponent.getUniqueId());
686                     return false;
687                 }
688                 substitutedName.append(groupOpt.get().getNormalizedName()).append(PATH_DELIMITER);
689             } else {
690                 logger.debug("Failed to find an capability owner with uniqueId {} on a component with uniqueId {}", ownerId,
691                     originComponent.getUniqueId());
692                 return false;
693             }
694         }
695         return true;
696     }
697
698     Either<Component, Boolean> getOriginComponent(Map<String, Component> componentsCache, ComponentInstance instance) {
699         Either<Component, Boolean> result;
700         Either<Component, StorageOperationStatus> getOriginRes;
701         if (componentsCache.containsKey(instance.getActualComponentUid())) {
702             result = Either.left(componentsCache.get(instance.getActualComponentUid()));
703         } else {
704             ComponentParametersView filter = getFilter(instance);
705             getOriginRes = toscaOperationFacade.getToscaElement(instance.getActualComponentUid(), filter);
706             if (getOriginRes.isRight()) {
707                 logger.debug("Failed to get an origin component with uniqueId {}", instance.getActualComponentUid());
708                 result = Either.right(false);
709             } else {
710                 result = Either.left(getOriginRes.left().value());
711                 componentsCache.put(getOriginRes.left().value().getUniqueId(), getOriginRes.left().value());
712             }
713         }
714         return result;
715     }
716
717     private ComponentParametersView getFilter(ComponentInstance instance) {
718         ComponentParametersView filter = new ComponentParametersView(true);
719         filter.setIgnoreComponentInstances(false);
720         if (instance.getIsProxy()) {
721             filter.setIgnoreCapabilities(false);
722             filter.setIgnoreRequirements(false);
723             filter.setIgnoreCategories(false);
724         }
725         if (instance.getOriginType() == OriginTypeEnum.VF) {
726             filter.setIgnoreGroups(false);
727         }
728         return filter;
729     }
730 }