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