9365fac4fc2d4967a822ea82673cbc3f34ed06b7
[sdc.git] / catalog-be / src / main / java / org / openecomp / sdc / be / components / impl / ServiceImportParseLogic.java
1 /*
2  * Copyright (C) 2020 CMCC, Inc. and others. All rights reserved.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 package org.openecomp.sdc.be.components.impl;
17
18 import static java.util.stream.Collectors.joining;
19 import static java.util.stream.Collectors.toList;
20 import static java.util.stream.Collectors.toMap;
21 import static org.apache.commons.collections.CollectionUtils.isNotEmpty;
22
23 import fj.data.Either;
24 import java.util.ArrayList;
25 import java.util.EnumMap;
26 import java.util.HashMap;
27 import java.util.Iterator;
28 import java.util.List;
29 import java.util.ListIterator;
30 import java.util.Map;
31 import java.util.Optional;
32 import java.util.Set;
33 import java.util.function.Function;
34 import lombok.Getter;
35 import org.apache.commons.codec.binary.Base64;
36 import org.apache.commons.collections.CollectionUtils;
37 import org.apache.commons.collections.MapUtils;
38 import org.apache.commons.lang3.StringUtils;
39 import org.apache.commons.lang3.tuple.ImmutablePair;
40 import org.openecomp.sdc.be.components.csar.CsarInfo;
41 import org.openecomp.sdc.be.components.impl.artifact.ArtifactOperationInfo;
42 import org.openecomp.sdc.be.components.impl.exceptions.BusinessLogicException;
43 import org.openecomp.sdc.be.components.impl.exceptions.ByResponseFormatComponentException;
44 import org.openecomp.sdc.be.components.impl.exceptions.ComponentException;
45 import org.openecomp.sdc.be.components.lifecycle.LifecycleBusinessLogic;
46 import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoWithAction;
47 import org.openecomp.sdc.be.config.BeEcompErrorManager;
48 import org.openecomp.sdc.be.config.ConfigurationManager;
49 import org.openecomp.sdc.be.dao.api.ActionStatus;
50 import org.openecomp.sdc.be.datatypes.elements.ArtifactDataDefinition;
51 import org.openecomp.sdc.be.datatypes.elements.CapabilityDataDefinition;
52 import org.openecomp.sdc.be.datatypes.elements.GetInputValueDataDefinition;
53 import org.openecomp.sdc.be.datatypes.elements.ListCapabilityDataDefinition;
54 import org.openecomp.sdc.be.datatypes.elements.ListDataDefinition;
55 import org.openecomp.sdc.be.datatypes.elements.ListRequirementDataDefinition;
56 import org.openecomp.sdc.be.datatypes.elements.MapInterfaceDataDefinition;
57 import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
58 import org.openecomp.sdc.be.datatypes.elements.RequirementDataDefinition;
59 import org.openecomp.sdc.be.datatypes.elements.SubstitutionFilterPropertyDataDefinition;
60 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
61 import org.openecomp.sdc.be.datatypes.enums.CreatedFrom;
62 import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
63 import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
64 import org.openecomp.sdc.be.impl.ComponentsUtils;
65 import org.openecomp.sdc.be.model.ArtifactDefinition;
66 import org.openecomp.sdc.be.model.AttributeDefinition;
67 import org.openecomp.sdc.be.model.CapabilityDefinition;
68 import org.openecomp.sdc.be.model.CapabilityRequirementRelationship;
69 import org.openecomp.sdc.be.model.CapabilityTypeDefinition;
70 import org.openecomp.sdc.be.model.Component;
71 import org.openecomp.sdc.be.model.ComponentInstance;
72 import org.openecomp.sdc.be.model.ComponentInstanceInput;
73 import org.openecomp.sdc.be.model.ComponentInstanceProperty;
74 import org.openecomp.sdc.be.model.ComponentParametersView;
75 import org.openecomp.sdc.be.model.GroupDefinition;
76 import org.openecomp.sdc.be.model.InputDefinition;
77 import org.openecomp.sdc.be.model.InterfaceDefinition;
78 import org.openecomp.sdc.be.model.LifeCycleTransitionEnum;
79 import org.openecomp.sdc.be.model.LifecycleStateEnum;
80 import org.openecomp.sdc.be.model.NodeTypeInfo;
81 import org.openecomp.sdc.be.model.Operation;
82 import org.openecomp.sdc.be.model.OutputDefinition;
83 import org.openecomp.sdc.be.model.PropertyDefinition;
84 import org.openecomp.sdc.be.model.RelationshipImpl;
85 import org.openecomp.sdc.be.model.RelationshipInfo;
86 import org.openecomp.sdc.be.model.RequirementCapabilityRelDef;
87 import org.openecomp.sdc.be.model.RequirementDefinition;
88 import org.openecomp.sdc.be.model.Resource;
89 import org.openecomp.sdc.be.model.Service;
90 import org.openecomp.sdc.be.model.UploadCapInfo;
91 import org.openecomp.sdc.be.model.UploadComponentInstanceInfo;
92 import org.openecomp.sdc.be.model.UploadInfo;
93 import org.openecomp.sdc.be.model.UploadNodeFilterInfo;
94 import org.openecomp.sdc.be.model.UploadPropInfo;
95 import org.openecomp.sdc.be.model.UploadReqInfo;
96 import org.openecomp.sdc.be.model.UploadResourceInfo;
97 import org.openecomp.sdc.be.model.User;
98 import org.openecomp.sdc.be.model.category.CategoryDefinition;
99 import org.openecomp.sdc.be.model.category.SubCategoryDefinition;
100 import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade;
101 import org.openecomp.sdc.be.model.jsonjanusgraph.utils.ModelConverter;
102 import org.openecomp.sdc.be.model.operations.api.ICapabilityTypeOperation;
103 import org.openecomp.sdc.be.model.operations.api.IInterfaceLifecycleOperation;
104 import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
105 import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder;
106 import org.openecomp.sdc.be.model.operations.utils.ComponentValidationUtils;
107 import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
108 import org.openecomp.sdc.be.resources.data.auditing.model.ResourceVersionInfo;
109 import org.openecomp.sdc.be.tosca.CsarUtils;
110 import org.openecomp.sdc.be.utils.CommonBeUtils;
111 import org.openecomp.sdc.be.utils.TypeUtils;
112 import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum;
113 import org.openecomp.sdc.common.api.Constants;
114 import org.openecomp.sdc.common.log.wrappers.Logger;
115 import org.openecomp.sdc.common.util.GeneralUtility;
116 import org.openecomp.sdc.common.util.ValidationUtils;
117 import org.openecomp.sdc.exception.ResponseFormat;
118 import org.yaml.snakeyaml.DumperOptions;
119 import org.yaml.snakeyaml.Yaml;
120
121 @Getter
122 @org.springframework.stereotype.Component
123 public class ServiceImportParseLogic {
124
125     private static final String INITIAL_VERSION = "0.1";
126     private static final String CREATE_RESOURCE = "Create Resource";
127     private static final String IN_RESOURCE = "  in resource {} ";
128     private static final String COMPONENT_INSTANCE_WITH_NAME = "component instance with name ";
129     private static final String COMPONENT_INSTANCE_WITH_NAME_IN_RESOURCE = "component instance with name {}  in resource {} ";
130     private static final String CERTIFICATION_ON_IMPORT = "certification on import";
131     private static final String VALIDATE_DERIVED_BEFORE_UPDATE = "validate derived before update";
132     private static final String PLACE_HOLDER_RESOURCE_TYPES = "validForResourceTypes";
133     private static final String CREATE_RESOURCE_VALIDATE_CAPABILITY_TYPES = "Create Resource - validateCapabilityTypesCreate";
134     private static final String CATEGORY_IS_EMPTY = "Resource category is empty";
135     private static final Logger log = Logger.getLogger(ServiceImportParseLogic.class);
136     private final ServiceBusinessLogic serviceBusinessLogic;
137     private final ComponentsUtils componentsUtils;
138     private final ToscaOperationFacade toscaOperationFacade;
139     private final LifecycleBusinessLogic lifecycleBusinessLogic;
140     private final InputsBusinessLogic inputsBusinessLogic;
141     private final ResourceImportManager resourceImportManager;
142     private final ComponentSubstitutionFilterBusinessLogic substitutionFilterBusinessLogic;
143     private final IInterfaceLifecycleOperation interfaceTypeOperation;
144     private final ICapabilityTypeOperation capabilityTypeOperation;
145     private final ComponentNodeFilterBusinessLogic componentNodeFilterBusinessLogic;
146     private final GroupBusinessLogic groupBusinessLogic;
147     private final OutputsBusinessLogic outputsBusinessLogic;
148
149     public ServiceImportParseLogic(final ServiceBusinessLogic serviceBusinessLogic, final ComponentsUtils componentsUtils,
150                                    final ToscaOperationFacade toscaOperationFacade, final LifecycleBusinessLogic lifecycleBusinessLogic,
151                                    final InputsBusinessLogic inputsBusinessLogic, final ResourceImportManager resourceImportManager,
152                                    final ComponentSubstitutionFilterBusinessLogic substitutionFilterBusinessLogic,
153                                    final IInterfaceLifecycleOperation interfaceTypeOperation, final ICapabilityTypeOperation capabilityTypeOperation,
154                                    final ComponentNodeFilterBusinessLogic componentNodeFilterBusinessLogic,
155                                    final GroupBusinessLogic groupBusinessLogic, final OutputsBusinessLogic outputsBusinessLogic) {
156         this.serviceBusinessLogic = serviceBusinessLogic;
157         this.componentsUtils = componentsUtils;
158         this.toscaOperationFacade = toscaOperationFacade;
159         this.lifecycleBusinessLogic = lifecycleBusinessLogic;
160         this.inputsBusinessLogic = inputsBusinessLogic;
161         this.resourceImportManager = resourceImportManager;
162         this.substitutionFilterBusinessLogic = substitutionFilterBusinessLogic;
163         this.interfaceTypeOperation = interfaceTypeOperation;
164         this.capabilityTypeOperation = capabilityTypeOperation;
165         this.componentNodeFilterBusinessLogic = componentNodeFilterBusinessLogic;
166         this.groupBusinessLogic = groupBusinessLogic;
167         this.outputsBusinessLogic = outputsBusinessLogic;
168     }
169
170     public Either<Map<String, EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>>>, ResponseFormat> findNodeTypesArtifactsToHandle(
171         Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo, Service oldResource) {
172         Map<String, EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle = new HashMap<>();
173         Either<Map<String, EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>>>, ResponseFormat> nodeTypesArtifactsToHandleRes = Either
174             .left(nodeTypesArtifactsToHandle);
175         try {
176             Map<String, List<ArtifactDefinition>> extractedVfcsArtifacts = CsarUtils.extractVfcsArtifactsFromCsar(csarInfo.getCsar());
177             Map<String, ImmutablePair<String, String>> extractedVfcToscaNames = extractVfcToscaNames(nodeTypesInfo, oldResource.getName(), csarInfo);
178             log.debug("Going to fetch node types for resource with name {} during import csar with UUID {}. ", oldResource.getName(),
179                 csarInfo.getCsarUUID());
180             extractedVfcToscaNames.forEach(
181                 (namespace, vfcToscaNames) -> findAddNodeTypeArtifactsToHandle(csarInfo, nodeTypesArtifactsToHandle, oldResource,
182                     extractedVfcsArtifacts, namespace, vfcToscaNames));
183         } catch (Exception e) {
184             ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
185             nodeTypesArtifactsToHandleRes = Either.right(responseFormat);
186             log.debug("Exception occured when findNodeTypesUpdatedArtifacts, error is:{}", e.getMessage(), e);
187         }
188         return nodeTypesArtifactsToHandleRes;
189     }
190
191     private Map<String, ImmutablePair<String, String>> extractVfcToscaNames(Map<String, NodeTypeInfo> nodeTypesInfo, String vfResourceName,
192                                                                             CsarInfo csarInfo) {
193         Map<String, ImmutablePair<String, String>> vfcToscaNames = new HashMap<>();
194         Map<String, Object> nodes = extractAllNodes(nodeTypesInfo, csarInfo);
195         if (!nodes.isEmpty()) {
196             Iterator<Map.Entry<String, Object>> nodesNameEntry = nodes.entrySet().iterator();
197             while (nodesNameEntry.hasNext()) {
198                 Map.Entry<String, Object> nodeType = nodesNameEntry.next();
199                 ImmutablePair<String, String> toscaResourceName = buildNestedToscaResourceName(ResourceTypeEnum.VFC.name(), vfResourceName,
200                     nodeType.getKey());
201                 vfcToscaNames.put(nodeType.getKey(), toscaResourceName);
202             }
203         }
204         for (NodeTypeInfo cvfc : nodeTypesInfo.values()) {
205             vfcToscaNames.put(cvfc.getType(), buildNestedToscaResourceName(ResourceTypeEnum.VF.name(), vfResourceName, cvfc.getType()));
206         }
207         return vfcToscaNames;
208     }
209
210     public String buildNodeTypeYaml(Map.Entry<String, Object> nodeNameValue, Map<String, Object> mapToConvert, String nodeResourceType,
211                                     CsarInfo csarInfo) {
212         // We need to create a Yaml from each node_types in order to create
213
214         // resource from each node type using import normative flow.
215         DumperOptions options = new DumperOptions();
216         options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
217         Yaml yaml = new Yaml(options);
218         Map<String, Object> node = new HashMap<>();
219         node.put(buildNestedToscaResourceName(nodeResourceType, csarInfo.getVfResourceName(), nodeNameValue.getKey()).getLeft(),
220             nodeNameValue.getValue());
221         mapToConvert.put(TypeUtils.ToscaTagNamesEnum.NODE_TYPES.getElementName(), node);
222         return yaml.dumpAsMap(mapToConvert);
223     }
224
225     ImmutablePair<String, String> buildNestedToscaResourceName(String nodeResourceType, String vfResourceName, String nodeTypeFullName) {
226         String actualType;
227         String actualVfName;
228         if (ResourceTypeEnum.CVFC.name().equals(nodeResourceType)) {
229             actualVfName = vfResourceName + ResourceTypeEnum.CVFC.name();
230             actualType = ResourceTypeEnum.VFC.name();
231         } else {
232             actualVfName = vfResourceName;
233             actualType = nodeResourceType;
234         }
235         String nameWithouNamespacePrefix;
236         try {
237             StringBuilder toscaResourceName = new StringBuilder(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX);
238             if (!nodeTypeFullName.contains(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX)) {
239                 nameWithouNamespacePrefix = nodeTypeFullName;
240             } else {
241                 nameWithouNamespacePrefix = nodeTypeFullName.substring(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX.length());
242             }
243             String[] findTypes = nameWithouNamespacePrefix.split("\\.");
244             String resourceType = findTypes[0];
245             String actualName = nameWithouNamespacePrefix.substring(resourceType.length());
246             if (actualName.startsWith(Constants.ABSTRACT)) {
247                 toscaResourceName.append(resourceType.toLowerCase()).append('.').append(ValidationUtils.convertToSystemName(actualVfName));
248             } else {
249                 toscaResourceName.append(actualType.toLowerCase()).append('.').append(ValidationUtils.convertToSystemName(actualVfName));
250             }
251             StringBuilder previousToscaResourceName = new StringBuilder(toscaResourceName);
252             return new ImmutablePair<>(toscaResourceName.append(actualName.toLowerCase()).toString(),
253                 previousToscaResourceName.append(actualName.substring(actualName.split("\\.")[1].length() + 1).toLowerCase()).toString());
254         } catch (Exception e) {
255             componentsUtils.getResponseFormat(ActionStatus.INVALID_TOSCA_TEMPLATE);
256             log.debug("Exception occured when buildNestedToscaResourceName, error is:{}", e.getMessage(), e);
257             throw new ComponentException(ActionStatus.INVALID_TOSCA_TEMPLATE, vfResourceName);
258         }
259     }
260
261     private Map<String, Object> extractAllNodes(Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo) {
262         Map<String, Object> nodes = new HashMap<>();
263         for (NodeTypeInfo nodeTypeInfo : nodeTypesInfo.values()) {
264             extractNodeTypes(nodes, nodeTypeInfo.getMappedToscaTemplate());
265         }
266         extractNodeTypes(nodes, csarInfo.getMappedToscaMainTemplate());
267         return nodes;
268     }
269
270     private void extractNodeTypes(Map<String, Object> nodes, Map<String, Object> mappedToscaTemplate) {
271         Either<Map<String, Object>, ImportUtils.ResultStatusEnum> eitherNodeTypes = ImportUtils
272             .findFirstToscaMapElement(mappedToscaTemplate, TypeUtils.ToscaTagNamesEnum.NODE_TYPES);
273         if (eitherNodeTypes.isLeft()) {
274             nodes.putAll(eitherNodeTypes.left().value());
275         }
276     }
277
278     protected void findAddNodeTypeArtifactsToHandle(CsarInfo csarInfo,
279                                                     Map<String, EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle,
280                                                     Service resource, Map<String, List<ArtifactDefinition>> extractedVfcsArtifacts, String namespace,
281                                                     ImmutablePair<String, String> vfcToscaNames) {
282         EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>> curNodeTypeArtifactsToHandle = null;
283         log.debug("Going to fetch node type with tosca name {}. ", vfcToscaNames.getLeft());
284         Resource curNodeType = findVfcResource(csarInfo, resource, vfcToscaNames.getLeft(), vfcToscaNames.getRight(), null);
285         if (!MapUtils.isEmpty(extractedVfcsArtifacts)) {
286             List<ArtifactDefinition> currArtifacts = new ArrayList<>();
287             if (extractedVfcsArtifacts.containsKey(namespace)) {
288                 handleAndAddExtractedVfcsArtifacts(currArtifacts, extractedVfcsArtifacts.get(namespace));
289             }
290             curNodeTypeArtifactsToHandle = findNodeTypeArtifactsToHandle(curNodeType, currArtifacts);
291         } else if (curNodeType != null) {
292             // delete all artifacts if have not received artifacts from
293
294             // csar
295             try {
296                 curNodeTypeArtifactsToHandle = new EnumMap<>(ArtifactsBusinessLogic.ArtifactOperationEnum.class);
297                 List<ArtifactDefinition> artifactsToDelete = new ArrayList<>();
298                 // delete all informational artifacts
299                 artifactsToDelete.addAll(
300                     curNodeType.getArtifacts().values().stream().filter(a -> a.getArtifactGroupType() == ArtifactGroupTypeEnum.INFORMATIONAL)
301                         .collect(toList()));
302                 // delete all deployment artifacts
303                 artifactsToDelete.addAll(curNodeType.getDeploymentArtifacts().values());
304                 if (!artifactsToDelete.isEmpty()) {
305                     curNodeTypeArtifactsToHandle.put(ArtifactsBusinessLogic.ArtifactOperationEnum.DELETE, artifactsToDelete);
306                 }
307             } catch (Exception e) {
308                 componentsUtils.getResponseFormat(ActionStatus.INVALID_TOSCA_TEMPLATE);
309                 log.debug("Exception occured when findAddNodeTypeArtifactsToHandle, error is:{}", e.getMessage(), e);
310                 throw new ComponentException(ActionStatus.INVALID_TOSCA_TEMPLATE, vfcToscaNames.getLeft());
311             }
312         }
313         if (MapUtils.isNotEmpty(curNodeTypeArtifactsToHandle)) {
314             nodeTypesArtifactsToHandle.put(namespace, curNodeTypeArtifactsToHandle);
315         }
316     }
317
318     protected void handleAndAddExtractedVfcsArtifacts(List<ArtifactDefinition> vfcArtifacts, List<ArtifactDefinition> artifactsToAdd) {
319         List<String> vfcArtifactNames = vfcArtifacts.stream().map(ArtifactDataDefinition::getArtifactName).collect(toList());
320         artifactsToAdd.stream().forEach(a -> {
321             if (!vfcArtifactNames.contains(a.getArtifactName())) {
322                 vfcArtifacts.add(a);
323             } else {
324                 log.debug("Can't upload two artifact with the same name {}. ", a.getArtifactName());
325             }
326         });
327     }
328
329     protected Resource findVfcResource(CsarInfo csarInfo, Service resource, String currVfcToscaName, String previousVfcToscaName,
330                                        StorageOperationStatus status) {
331         if (status != null && status != StorageOperationStatus.NOT_FOUND) {
332             log.debug("Error occured during fetching node type with tosca name {}, error: {}", currVfcToscaName, status);
333             throw new ComponentException(componentsUtils.convertFromStorageResponse(status), csarInfo.getCsarUUID());
334         } else if (org.apache.commons.lang.StringUtils.isNotEmpty(currVfcToscaName)) {
335             return (Resource) toscaOperationFacade.getLatestByToscaResourceName(currVfcToscaName, resource.getModel()).left()
336                 .on(st -> findVfcResource(csarInfo, resource, previousVfcToscaName, null, st));
337         }
338         return null;
339     }
340
341     protected EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>> findNodeTypeArtifactsToHandle(Resource curNodeType,
342                                                                                                                             List<ArtifactDefinition> extractedArtifacts) {
343         EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle = null;
344         try {
345             List<ArtifactDefinition> artifactsToUpload = new ArrayList<>(extractedArtifacts);
346             List<ArtifactDefinition> artifactsToUpdate = new ArrayList<>();
347             List<ArtifactDefinition> artifactsToDelete = new ArrayList<>();
348             processExistingNodeTypeArtifacts(extractedArtifacts, artifactsToUpload, artifactsToUpdate, artifactsToDelete,
349                 collectExistingArtifacts(curNodeType));
350             nodeTypeArtifactsToHandle = putFoundArtifacts(artifactsToUpload, artifactsToUpdate, artifactsToDelete);
351         } catch (Exception e) {
352             log.debug("Exception occured when findNodeTypeArtifactsToHandle, error is:{}", e.getMessage(), e);
353             throw new ComponentException(ActionStatus.GENERAL_ERROR);
354         }
355         return nodeTypeArtifactsToHandle;
356     }
357
358     protected Map<String, ArtifactDefinition> collectExistingArtifacts(Resource curNodeType) {
359         Map<String, ArtifactDefinition> existingArtifacts = new HashMap<>();
360         if (curNodeType == null) {
361             return existingArtifacts;
362         }
363         if (MapUtils.isNotEmpty(curNodeType.getDeploymentArtifacts())) {
364             existingArtifacts.putAll(curNodeType.getDeploymentArtifacts());
365         }
366         if (MapUtils.isNotEmpty(curNodeType.getArtifacts())) {
367             existingArtifacts.putAll(
368                 curNodeType.getArtifacts().entrySet().stream().filter(e -> e.getValue().getArtifactGroupType() == ArtifactGroupTypeEnum.INFORMATIONAL)
369                     .collect(toMap(Map.Entry::getKey, Map.Entry::getValue)));
370         }
371         return existingArtifacts;
372     }
373
374     protected EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>> putFoundArtifacts(
375         List<ArtifactDefinition> artifactsToUpload, List<ArtifactDefinition> artifactsToUpdate, List<ArtifactDefinition> artifactsToDelete) {
376         EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle = null;
377         if (!artifactsToUpload.isEmpty() || !artifactsToUpdate.isEmpty() || !artifactsToDelete.isEmpty()) {
378             nodeTypeArtifactsToHandle = new EnumMap<>(ArtifactsBusinessLogic.ArtifactOperationEnum.class);
379             if (!artifactsToUpload.isEmpty()) {
380                 nodeTypeArtifactsToHandle.put(ArtifactsBusinessLogic.ArtifactOperationEnum.CREATE, artifactsToUpload);
381             }
382             if (!artifactsToUpdate.isEmpty()) {
383                 nodeTypeArtifactsToHandle.put(ArtifactsBusinessLogic.ArtifactOperationEnum.UPDATE, artifactsToUpdate);
384             }
385             if (!artifactsToDelete.isEmpty()) {
386                 nodeTypeArtifactsToHandle.put(ArtifactsBusinessLogic.ArtifactOperationEnum.DELETE, artifactsToDelete);
387             }
388         }
389         return nodeTypeArtifactsToHandle;
390     }
391
392     protected void processExistingNodeTypeArtifacts(List<ArtifactDefinition> extractedArtifacts, List<ArtifactDefinition> artifactsToUpload,
393                                                     List<ArtifactDefinition> artifactsToUpdate, List<ArtifactDefinition> artifactsToDelete,
394                                                     Map<String, ArtifactDefinition> existingArtifacts) {
395         try {
396             if (!existingArtifacts.isEmpty()) {
397                 extractedArtifacts.stream().forEach(a -> processNodeTypeArtifact(artifactsToUpload, artifactsToUpdate, existingArtifacts, a));
398                 artifactsToDelete.addAll(existingArtifacts.values());
399             }
400         } catch (Exception e) {
401             log.debug("Exception occured when processExistingNodeTypeArtifacts, error is:{}", e.getMessage(), e);
402             throw new ComponentException(ActionStatus.GENERAL_ERROR);
403         }
404     }
405
406     protected void processNodeTypeArtifact(List<ArtifactDefinition> artifactsToUpload, List<ArtifactDefinition> artifactsToUpdate,
407                                            Map<String, ArtifactDefinition> existingArtifacts, ArtifactDefinition currNewArtifact) {
408         Optional<ArtifactDefinition> foundArtifact = existingArtifacts.values().stream()
409             .filter(a -> a.getArtifactName().equals(currNewArtifact.getArtifactName())).findFirst();
410         if (foundArtifact.isPresent()) {
411             if (foundArtifact.get().getArtifactType().equals(currNewArtifact.getArtifactType())) {
412                 updateFoundArtifact(artifactsToUpdate, currNewArtifact, foundArtifact.get());
413                 existingArtifacts.remove(foundArtifact.get().getArtifactLabel());
414                 artifactsToUpload.remove(currNewArtifact);
415             } else {
416                 log.debug("Can't upload two artifact with the same name {}.", currNewArtifact.getArtifactName());
417                 throw new ComponentException(ActionStatus.ARTIFACT_ALREADY_EXIST_IN_DIFFERENT_TYPE_IN_CSAR, currNewArtifact.getArtifactName(),
418                     currNewArtifact.getArtifactType(), foundArtifact.get().getArtifactType());
419             }
420         }
421     }
422
423     protected void updateFoundArtifact(List<ArtifactDefinition> artifactsToUpdate, ArtifactDefinition currNewArtifact,
424                                        ArtifactDefinition foundArtifact) {
425         if (!foundArtifact.getArtifactChecksum().equals(currNewArtifact.getArtifactChecksum())) {
426             foundArtifact.setPayload(currNewArtifact.getPayloadData());
427             foundArtifact.setPayloadData(Base64.encodeBase64String(currNewArtifact.getPayloadData()));
428             foundArtifact.setArtifactChecksum(GeneralUtility.calculateMD5Base64EncodedByByteArray(currNewArtifact.getPayloadData()));
429             artifactsToUpdate.add(foundArtifact);
430         }
431     }
432
433     public void addNonMetaCreatedArtifactsToSupportRollback(ArtifactOperationInfo operation, List<ArtifactDefinition> createdArtifacts,
434                                                             Either<Either<ArtifactDefinition, Operation>, ResponseFormat> eitherNonMetaArtifacts) {
435         if (ArtifactsBusinessLogic.ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum()) && createdArtifacts != null
436             && eitherNonMetaArtifacts.isLeft()) {
437             Either<ArtifactDefinition, Operation> eitherResult = eitherNonMetaArtifacts.left().value();
438             if (eitherResult.isLeft()) {
439                 createdArtifacts.add(eitherResult.left().value());
440             }
441         }
442     }
443
444     public boolean isArtifactDeletionRequired(String artifactId, byte[] artifactFileBytes, boolean isFromCsar) {
445         return !org.apache.commons.lang.StringUtils.isEmpty(artifactId) && artifactFileBytes == null && isFromCsar;
446     }
447
448     public void fillGroupsFinalFields(List<GroupDefinition> groupsAsList) {
449         groupsAsList.forEach(groupDefinition -> {
450             groupDefinition.setInvariantName(groupDefinition.getName());
451             groupDefinition.setCreatedFrom(CreatedFrom.CSAR);
452         });
453     }
454
455     public String getComponentTypeForResponse(Component component) {
456         String componentTypeForResponse = "SERVICE";
457         if (component instanceof Resource) {
458             componentTypeForResponse = ((Resource) component).getResourceType().name();
459         }
460         return componentTypeForResponse;
461     }
462
463     public Resource buildValidComplexVfc(Resource resource, CsarInfo csarInfo, String nodeName, Map<String, NodeTypeInfo> nodesInfo) {
464         Resource complexVfc = buildComplexVfcMetadata(resource, csarInfo, nodeName, nodesInfo);
465         log.debug("************* Going to validate complex VFC from yaml {}", complexVfc.getName());
466         csarInfo.addNodeToQueue(nodeName);
467         return validateResourceBeforeCreate(complexVfc, csarInfo.getModifier(), AuditingActionEnum.IMPORT_RESOURCE, true, csarInfo);
468     }
469
470     public Resource validateResourceBeforeCreate(Resource resource, User user, AuditingActionEnum actionEnum, boolean inTransaction,
471                                                  CsarInfo csarInfo) {
472         validateResourceFieldsBeforeCreate(user, resource, actionEnum, inTransaction);
473         validateCapabilityTypesCreate(user, getCapabilityTypeOperation(), resource, actionEnum, inTransaction);
474         validateLifecycleTypesCreate(user, resource, actionEnum);
475         validateResourceType(user, resource, actionEnum);
476         resource.setCreatorUserId(user.getUserId());
477         resource.setCreatorFullName(user.getFirstName() + " " + user.getLastName());
478         resource.setContactId(resource.getContactId().toLowerCase());
479         if (org.apache.commons.lang.StringUtils.isEmpty(resource.getToscaResourceName()) && !ModelConverter.isAtomicComponent(resource)) {
480             String resourceSystemName;
481             if (csarInfo != null && org.apache.commons.lang.StringUtils.isNotEmpty(csarInfo.getVfResourceName())) {
482                 resourceSystemName = ValidationUtils.convertToSystemName(csarInfo.getVfResourceName());
483             } else {
484                 resourceSystemName = resource.getSystemName();
485             }
486             resource
487                 .setToscaResourceName(CommonBeUtils.generateToscaResourceName(resource.getResourceType().name().toLowerCase(), resourceSystemName));
488         }
489         // Generate invariant UUID - must be here and not in operation since it
490
491         // should stay constant during clone
492
493         // TODO
494         String invariantUUID = UniqueIdBuilder.buildInvariantUUID();
495         resource.setInvariantUUID(invariantUUID);
496         return resource;
497     }
498
499     protected Either<Boolean, ResponseFormat> validateResourceType(User user, Resource resource, AuditingActionEnum actionEnum) {
500         Either<Boolean, ResponseFormat> eitherResult = Either.left(true);
501         if (resource.getResourceType() == null) {
502             log.debug("Invalid resource type for resource");
503             ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
504             eitherResult = Either.right(errorResponse);
505             componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
506         }
507         return eitherResult;
508     }
509
510     protected Either<Boolean, ResponseFormat> validateLifecycleTypesCreate(User user, Resource resource, AuditingActionEnum actionEnum) {
511         Either<Boolean, ResponseFormat> eitherResult = Either.left(true);
512         if (resource.getInterfaces() != null && resource.getInterfaces().size() > 0) {
513             log.debug("validate interface lifecycle Types Exist");
514             Iterator<InterfaceDefinition> intItr = resource.getInterfaces().values().iterator();
515             while (intItr.hasNext() && eitherResult.isLeft()) {
516                 InterfaceDefinition interfaceDefinition = intItr.next();
517                 String intType = interfaceDefinition.getUniqueId();
518                 Either<InterfaceDefinition, StorageOperationStatus> eitherCapTypeFound = interfaceTypeOperation.getInterface(
519                     UniqueIdBuilder.buildInterfaceTypeUid(resource.getModel(), intType));
520                 if (eitherCapTypeFound.isRight()) {
521                     if (eitherCapTypeFound.right().value() == StorageOperationStatus.NOT_FOUND) {
522                         BeEcompErrorManager.getInstance()
523                             .logBeGraphObjectMissingError("Create Resource - validateLifecycleTypesCreate", "Interface", intType);
524                         log.debug("Lifecycle Type: {} is required by resource: {} but does not exist in the DB", intType, resource.getName());
525                         BeEcompErrorManager.getInstance().logBeDaoSystemError("Create Resource - validateLifecycleTypesCreate");
526                         log.debug("request to data model failed with error: {}", eitherCapTypeFound.right().value().name());
527                     }
528                     ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_LIFECYCLE_TYPE, intType);
529                     eitherResult = Either.right(errorResponse);
530                     componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
531                 }
532             }
533         }
534         return eitherResult;
535     }
536
537     public Either<Boolean, ResponseFormat> validateCapabilityTypesCreate(User user, ICapabilityTypeOperation capabilityTypeOperation,
538                                                                          Resource resource, AuditingActionEnum actionEnum, boolean inTransaction) {
539         Either<Boolean, ResponseFormat> eitherResult = Either.left(true);
540         if (resource.getCapabilities() != null && resource.getCapabilities().size() > 0) {
541             log.debug("validate capability Types Exist - capabilities section");
542             for (Map.Entry<String, List<CapabilityDefinition>> typeEntry : resource.getCapabilities().entrySet()) {
543                 eitherResult = validateCapabilityTypeExists(user, capabilityTypeOperation, resource, actionEnum, eitherResult, typeEntry,
544                     inTransaction);
545                 if (eitherResult.isRight()) {
546                     return Either.right(eitherResult.right().value());
547                 }
548             }
549         }
550         if (resource.getRequirements() != null && resource.getRequirements().size() > 0) {
551             log.debug("validate capability Types Exist - requirements section");
552             for (String type : resource.getRequirements().keySet()) {
553                 eitherResult = validateCapabilityTypeExists(user, capabilityTypeOperation, resource, resource.getRequirements().get(type), actionEnum,
554                     eitherResult, type, inTransaction);
555                 if (eitherResult.isRight()) {
556                     return Either.right(eitherResult.right().value());
557                 }
558             }
559         }
560         return eitherResult;
561     }
562
563     protected Either<Boolean, ResponseFormat> validateCapabilityTypeExists(User user, ICapabilityTypeOperation capabilityTypeOperation,
564                                                                            Resource resource, AuditingActionEnum actionEnum,
565                                                                            Either<Boolean, ResponseFormat> eitherResult,
566                                                                            Map.Entry<String, List<CapabilityDefinition>> typeEntry,
567                                                                            boolean inTransaction) {
568         Either<CapabilityTypeDefinition, StorageOperationStatus> eitherCapTypeFound = capabilityTypeOperation
569             .getCapabilityType(UniqueIdBuilder.buildCapabilityTypeUid(resource.getModel(), typeEntry.getKey()), inTransaction);
570         if (eitherCapTypeFound.isRight()) {
571             if (eitherCapTypeFound.right().value() == StorageOperationStatus.NOT_FOUND) {
572                 BeEcompErrorManager.getInstance()
573                     .logBeGraphObjectMissingError(CREATE_RESOURCE_VALIDATE_CAPABILITY_TYPES, "Capability Type", typeEntry.getKey());
574                 log.debug("Capability Type: {} is required by resource: {} but does not exist in the DB", typeEntry.getKey(), resource.getName());
575                 BeEcompErrorManager.getInstance().logBeDaoSystemError(CREATE_RESOURCE_VALIDATE_CAPABILITY_TYPES);
576             }
577             log.debug("Trying to get capability type {} failed with error: {}", typeEntry.getKey(), eitherCapTypeFound.right().value().name());
578             ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_CAPABILITY_TYPE, typeEntry.getKey());
579             eitherResult = Either.right(errorResponse);
580             componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
581             return Either.right(eitherResult.right().value());
582         }
583         CapabilityTypeDefinition capabilityTypeDefinition = eitherCapTypeFound.left().value();
584         if (capabilityTypeDefinition.getProperties() != null) {
585             for (CapabilityDefinition capDef : typeEntry.getValue()) {
586                 List<ComponentInstanceProperty> properties = capDef.getProperties();
587                 if (properties == null || properties.isEmpty()) {
588                     properties = new ArrayList<>();
589                     for (Map.Entry<String, PropertyDefinition> prop : capabilityTypeDefinition.getProperties().entrySet()) {
590                         ComponentInstanceProperty newProp = new ComponentInstanceProperty(prop.getValue());
591                         properties.add(newProp);
592                     }
593                 } else {
594                     for (Map.Entry<String, PropertyDefinition> prop : capabilityTypeDefinition.getProperties().entrySet()) {
595                         PropertyDefinition porpFromDef = prop.getValue();
596                         List<ComponentInstanceProperty> propsToAdd = new ArrayList<>();
597                         for (ComponentInstanceProperty cip : properties) {
598                             if (!cip.getName().equals(porpFromDef.getName())) {
599                                 ComponentInstanceProperty newProp = new ComponentInstanceProperty(porpFromDef);
600                                 propsToAdd.add(newProp);
601                             }
602                         }
603                         if (!propsToAdd.isEmpty()) {
604                             properties.addAll(propsToAdd);
605                         }
606                     }
607                 }
608                 capDef.setProperties(properties);
609             }
610         }
611         return eitherResult;
612     }
613
614     protected Either<Boolean, ResponseFormat> validateCapabilityTypeExists(User user, ICapabilityTypeOperation capabilityTypeOperation,
615                                                                            Resource resource, List<?> validationObjects,
616                                                                            AuditingActionEnum actionEnum,
617                                                                            Either<Boolean, ResponseFormat> eitherResult, String type,
618                                                                            boolean inTransaction) {
619         try {
620             Either<CapabilityTypeDefinition, StorageOperationStatus> eitherCapTypeFound = capabilityTypeOperation
621                 .getCapabilityType(UniqueIdBuilder.buildCapabilityTypeUid(resource.getModel(), type), inTransaction);
622             if (eitherCapTypeFound.isRight()) {
623                 if (eitherCapTypeFound.right().value() == StorageOperationStatus.NOT_FOUND) {
624                     BeEcompErrorManager.getInstance()
625                         .logBeGraphObjectMissingError(CREATE_RESOURCE_VALIDATE_CAPABILITY_TYPES, "Capability Type", type);
626                     log.debug("Capability Type: {} is required by resource: {} but does not exist in the DB", type, resource.getName());
627                     BeEcompErrorManager.getInstance().logBeDaoSystemError(CREATE_RESOURCE_VALIDATE_CAPABILITY_TYPES);
628                 }
629                 log.debug("Trying to get capability type {} failed with error: {}", type, eitherCapTypeFound.right().value().name());
630                 ResponseFormat errorResponse = null;
631                 if (type != null) {
632                     errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_CAPABILITY_TYPE, type);
633                 } else {
634                     errorResponse = componentsUtils.getResponseFormatByElement(ActionStatus.MISSING_CAPABILITY_TYPE, validationObjects);
635                 }
636                 eitherResult = Either.right(errorResponse);
637                 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
638             }
639         } catch (Exception e) {
640             log.debug("Exception occured when validateCapabilityTypeExists, error is:{}", e.getMessage(), e);
641             throw new ComponentException(ActionStatus.INVALID_TOSCA_TEMPLATE, resource.getName());
642         }
643         return eitherResult;
644     }
645
646     protected Either<Boolean, ResponseFormat> validateResourceFieldsBeforeCreate(User user, Resource resource, AuditingActionEnum actionEnum,
647                                                                                  boolean inTransaction) {
648         serviceBusinessLogic.validateComponentFieldsBeforeCreate(user, resource, actionEnum);
649         // validate category
650         log.debug("validate category");
651         validateCategory(user, resource, actionEnum, inTransaction);
652         // validate vendor name & release & model number
653         log.debug("validate vendor name");
654         validateVendorName(user, resource, actionEnum);
655         log.debug("validate vendor release");
656         validateVendorReleaseName(user, resource, actionEnum);
657         log.debug("validate resource vendor model number");
658         validateResourceVendorModelNumber(user, resource, actionEnum);
659         // validate cost
660         log.debug("validate cost");
661         validateCost(resource);
662         // validate licenseType
663         log.debug("validate licenseType");
664         validateLicenseType(user, resource, actionEnum);
665         // validate template (derived from)
666         log.debug("validate derived from");
667         if (!ModelConverter.isAtomicComponent(resource) && resource.getResourceType() != ResourceTypeEnum.VF) {
668             resource.setDerivedFrom(null);
669         }
670         validateDerivedFromExist(user, resource, actionEnum);
671         serviceBusinessLogic.checkComponentFieldsForOverrideAttempt(resource);
672         String currentCreatorFullName = resource.getCreatorFullName();
673         if (currentCreatorFullName != null) {
674             log.debug("Resource Creator fullname is automatically set and cannot be updated");
675         }
676         String currentLastUpdaterFullName = resource.getLastUpdaterFullName();
677         if (currentLastUpdaterFullName != null) {
678             log.debug("Resource LastUpdater fullname is automatically set and cannot be updated");
679         }
680         Long currentLastUpdateDate = resource.getLastUpdateDate();
681         if (currentLastUpdateDate != null) {
682             log.debug("Resource last update date is automatically set and cannot be updated");
683         }
684         Boolean currentAbstract = resource.isAbstract();
685         if (currentAbstract != null) {
686             log.debug("Resource abstract is automatically set and cannot be updated");
687         }
688         return Either.left(true);
689     }
690
691     protected void validateDerivedFromExist(User user, Resource resource, AuditingActionEnum actionEnum) {
692         if (resource.getDerivedFrom() == null || resource.getDerivedFrom().isEmpty()) {
693             return;
694         }
695         String templateName = resource.getDerivedFrom().get(0);
696         Either<Boolean, StorageOperationStatus> dataModelResponse = toscaOperationFacade.validateToscaResourceNameExists(templateName);
697         if (dataModelResponse.isRight()) {
698             StorageOperationStatus storageStatus = dataModelResponse.right().value();
699             BeEcompErrorManager.getInstance().logBeDaoSystemError("Create Resource - validateDerivedFromExist");
700             log.debug("request to data model failed with error: {}", storageStatus);
701             ResponseFormat responseFormat = componentsUtils
702                 .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(storageStatus), resource);
703             log.trace("audit before sending response");
704             componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
705             throw new ComponentException(componentsUtils.convertFromStorageResponse(storageStatus));
706         } else if (!dataModelResponse.left().value()) {
707             log.info("resource template with name: {}, does not exists", templateName);
708             ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.PARENT_RESOURCE_NOT_FOUND);
709             componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
710             throw new ComponentException(ActionStatus.PARENT_RESOURCE_NOT_FOUND);
711         }
712     }
713
714     protected void validateLicenseType(User user, Resource resource, AuditingActionEnum actionEnum) {
715         log.debug("validate licenseType");
716         String licenseType = resource.getLicenseType();
717         if (licenseType != null) {
718             List<String> licenseTypes = ConfigurationManager.getConfigurationManager().getConfiguration().getLicenseTypes();
719             if (!licenseTypes.contains(licenseType)) {
720                 log.debug("License type {} isn't configured", licenseType);
721                 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
722                 if (actionEnum != null) {
723                     // In update case, no audit is required
724                     componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
725                 }
726                 throw new ComponentException(ActionStatus.INVALID_CONTENT);
727             }
728         }
729     }
730
731     protected void validateCost(Resource resource) {
732         String cost = resource.getCost();
733         if (cost != null) {
734             if (!ValidationUtils.validateCost(cost)) {
735                 log.debug("resource cost is invalid.");
736                 throw new ComponentException(ActionStatus.INVALID_CONTENT);
737             }
738         }
739     }
740
741     protected void validateResourceVendorModelNumber(User user, Resource resource, AuditingActionEnum actionEnum) {
742         String resourceVendorModelNumber = resource.getResourceVendorModelNumber();
743         if (org.apache.commons.lang.StringUtils.isNotEmpty(resourceVendorModelNumber)) {
744             if (!ValidationUtils.validateResourceVendorModelNumberLength(resourceVendorModelNumber)) {
745                 log.info("resource vendor model number exceeds limit.");
746                 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_VENDOR_MODEL_NUMBER_EXCEEDS_LIMIT,
747                     "" + ValidationUtils.RESOURCE_VENDOR_MODEL_NUMBER_MAX_LENGTH);
748                 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
749                 throw new ComponentException(ActionStatus.RESOURCE_VENDOR_MODEL_NUMBER_EXCEEDS_LIMIT,
750                     "" + ValidationUtils.RESOURCE_VENDOR_MODEL_NUMBER_MAX_LENGTH);
751             }
752             // resource vendor model number is currently validated as vendor
753
754             // name
755             if (!ValidationUtils.validateVendorName(resourceVendorModelNumber)) {
756                 log.info("resource vendor model number  is not valid.");
757                 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_RESOURCE_VENDOR_MODEL_NUMBER);
758                 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
759                 throw new ComponentException(ActionStatus.INVALID_RESOURCE_VENDOR_MODEL_NUMBER);
760             }
761         }
762     }
763
764     public void validateVendorReleaseName(User user, Resource resource, AuditingActionEnum actionEnum) {
765         String vendorRelease = resource.getVendorRelease();
766         log.debug("validate vendor relese name");
767         if (StringUtils.isEmpty(vendorRelease)) {
768             log.info("vendor relese name is missing.");
769             ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_VENDOR_RELEASE);
770             componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
771             throw new ComponentException(ActionStatus.MISSING_VENDOR_RELEASE);
772         }
773         validateVendorReleaseName(vendorRelease, user, resource, actionEnum);
774     }
775
776     public void validateVendorReleaseName(String vendorRelease, User user, Resource resource, AuditingActionEnum actionEnum) {
777         if (vendorRelease != null) {
778             if (!ValidationUtils.validateVendorReleaseLength(vendorRelease)) {
779                 log.info("vendor release exceds limit.");
780                 ResponseFormat errorResponse = componentsUtils
781                     .getResponseFormat(ActionStatus.VENDOR_RELEASE_EXCEEDS_LIMIT, "" + ValidationUtils.VENDOR_RELEASE_MAX_LENGTH);
782                 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
783                 throw new ComponentException(ActionStatus.VENDOR_RELEASE_EXCEEDS_LIMIT, "" + ValidationUtils.VENDOR_RELEASE_MAX_LENGTH);
784             }
785             if (!ValidationUtils.validateVendorRelease(vendorRelease)) {
786                 log.info("vendor release  is not valid.");
787                 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_VENDOR_RELEASE);
788                 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
789                 throw new ComponentException(ActionStatus.INVALID_VENDOR_RELEASE);
790             }
791         }
792     }
793
794     protected void validateCategory(User user, Resource resource, AuditingActionEnum actionEnum, boolean inTransaction) {
795         List<CategoryDefinition> categories = resource.getCategories();
796         if (CollectionUtils.isEmpty(categories)) {
797             log.debug(CATEGORY_IS_EMPTY);
798             ResponseFormat responseFormat = componentsUtils
799                 .getResponseFormat(ActionStatus.COMPONENT_MISSING_CATEGORY, ComponentTypeEnum.RESOURCE.getValue());
800             componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
801             throw new ComponentException(ActionStatus.COMPONENT_MISSING_CATEGORY, ComponentTypeEnum.RESOURCE.getValue());
802         }
803         if (categories.size() > 1) {
804             log.debug("Must be only one category for resource");
805             throw new ComponentException(ActionStatus.COMPONENT_TOO_MUCH_CATEGORIES, ComponentTypeEnum.RESOURCE.getValue());
806         }
807         CategoryDefinition category = categories.get(0);
808         List<SubCategoryDefinition> subcategories = category.getSubcategories();
809         if (CollectionUtils.isEmpty(subcategories)) {
810             log.debug("Missinig subcategory for resource");
811             throw new ComponentException(ActionStatus.COMPONENT_MISSING_SUBCATEGORY);
812         }
813         if (subcategories.size() > 1) {
814             log.debug("Must be only one sub category for resource");
815             throw new ComponentException(ActionStatus.RESOURCE_TOO_MUCH_SUBCATEGORIES);
816         }
817         SubCategoryDefinition subcategory = subcategories.get(0);
818         if (StringUtils.isEmpty(category.getName())) {
819             log.debug(CATEGORY_IS_EMPTY);
820             ResponseFormat responseFormat = componentsUtils
821                 .getResponseFormat(ActionStatus.COMPONENT_MISSING_CATEGORY, ComponentTypeEnum.RESOURCE.getValue());
822             componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
823             throw new ComponentException(ActionStatus.COMPONENT_MISSING_CATEGORY, ComponentTypeEnum.RESOURCE.getValue());
824         }
825         if (StringUtils.isEmpty(subcategory.getName())) {
826             log.debug(CATEGORY_IS_EMPTY);
827             ResponseFormat responseFormat = componentsUtils
828                 .getResponseFormat(ActionStatus.COMPONENT_MISSING_SUBCATEGORY, ComponentTypeEnum.RESOURCE.getValue());
829             componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
830             throw new ComponentException(ActionStatus.COMPONENT_MISSING_SUBCATEGORY, ComponentTypeEnum.RESOURCE.getValue());
831         }
832         validateCategoryListed(category, subcategory, user, resource, actionEnum, inTransaction);
833     }
834
835     protected void validateCategoryListed(CategoryDefinition category, SubCategoryDefinition subcategory, User user, Resource resource,
836                                           AuditingActionEnum actionEnum, boolean inTransaction) {
837         ResponseFormat responseFormat;
838         if (category != null && subcategory != null) {
839             try {
840                 log.debug("validating resource category {} against valid categories list", category);
841                 Either<List<CategoryDefinition>, ActionStatus> categories = serviceBusinessLogic.elementDao
842                     .getAllCategories(NodeTypeEnum.ResourceNewCategory, inTransaction);
843                 if (categories.isRight()) {
844                     log.debug("failed to retrieve resource categories from Titan");
845                     responseFormat = componentsUtils.getResponseFormat(categories.right().value());
846                     componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
847                     throw new ComponentException(categories.right().value());
848                 }
849                 List<CategoryDefinition> categoryList = categories.left().value();
850                 Optional<CategoryDefinition> foundCategory = categoryList.stream().filter(cat -> cat.getName().equals(category.getName()))
851                     .findFirst();
852                 if (!foundCategory.isPresent()) {
853                     log.debug("Category {} is not part of resource category group. Resource category valid values are {}", category, categoryList);
854                     failOnInvalidCategory(user, resource, actionEnum);
855                 }
856                 Optional<SubCategoryDefinition> foundSubcategory = foundCategory.get().getSubcategories().stream()
857                     .filter(subcat -> subcat.getName().equals(subcategory.getName())).findFirst();
858                 if (!foundSubcategory.isPresent()) {
859                     log.debug("SubCategory {} is not part of resource category group. Resource subcategory valid values are {}", subcategory,
860                         foundCategory.get().getSubcategories());
861                     failOnInvalidCategory(user, resource, actionEnum);
862                 }
863             } catch (Exception e) {
864                 log.debug("Exception occured when validateCategoryListed, error is:{}", e.getMessage(), e);
865                 throw new ComponentException(ActionStatus.GENERAL_ERROR);
866             }
867         }
868     }
869
870     protected void failOnInvalidCategory(User user, Resource resource, AuditingActionEnum actionEnum) {
871         ResponseFormat responseFormat;
872         responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INVALID_CATEGORY, ComponentTypeEnum.RESOURCE.getValue());
873         componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
874         throw new ComponentException(ActionStatus.COMPONENT_INVALID_CATEGORY, ComponentTypeEnum.RESOURCE.getValue());
875     }
876
877     protected void validateVendorName(User user, Resource resource, AuditingActionEnum actionEnum) {
878         String vendorName = resource.getVendorName();
879         if (StringUtils.isEmpty(vendorName)) {
880             log.info("vendor name is missing.");
881             ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_VENDOR_NAME);
882             componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
883             throw new ComponentException(ActionStatus.MISSING_VENDOR_NAME);
884         }
885         validateVendorName(vendorName, user, resource, actionEnum);
886     }
887
888     protected void validateVendorName(String vendorName, User user, Resource resource, AuditingActionEnum actionEnum) {
889         if (vendorName != null) {
890             if (!ValidationUtils.validateVendorNameLength(vendorName)) {
891                 log.info("vendor name exceds limit.");
892                 ResponseFormat errorResponse = componentsUtils
893                     .getResponseFormat(ActionStatus.VENDOR_NAME_EXCEEDS_LIMIT, "" + ValidationUtils.VENDOR_NAME_MAX_LENGTH);
894                 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
895                 throw new ComponentException(ActionStatus.VENDOR_NAME_EXCEEDS_LIMIT, "" + ValidationUtils.VENDOR_NAME_MAX_LENGTH);
896             }
897             if (!ValidationUtils.validateVendorName(vendorName)) {
898                 log.info("vendor name  is not valid.");
899                 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_VENDOR_NAME);
900                 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
901                 throw new ComponentException(ActionStatus.INVALID_VENDOR_NAME);
902             }
903         }
904     }
905
906     private Resource buildComplexVfcMetadata(Resource resourceVf, CsarInfo csarInfo, String nodeName, Map<String, NodeTypeInfo> nodesInfo) {
907         Resource cvfc = new Resource();
908         NodeTypeInfo nodeTypeInfo = nodesInfo.get(nodeName);
909         cvfc.setName(buildCvfcName(csarInfo.getVfResourceName(), nodeName));
910         cvfc.setNormalizedName(ValidationUtils.normaliseComponentName(cvfc.getName()));
911         cvfc.setSystemName(ValidationUtils.convertToSystemName(cvfc.getName()));
912         cvfc.setResourceType(ResourceTypeEnum.VF);
913         cvfc.setAbstract(true);
914         cvfc.setDerivedFrom(nodeTypeInfo.getDerivedFrom());
915         cvfc.setDescription(ImportUtils.Constants.CVFC_DESCRIPTION);
916         cvfc.setIcon(ImportUtils.Constants.DEFAULT_ICON);
917         cvfc.setContactId(csarInfo.getModifier().getUserId());
918         cvfc.setCreatorUserId(csarInfo.getModifier().getUserId());
919         cvfc.setVendorName(resourceVf.getVendorName());
920         cvfc.setTenant(resourceVf.getTenant());
921         cvfc.setVendorRelease(resourceVf.getVendorRelease());
922         cvfc.setResourceVendorModelNumber(resourceVf.getResourceVendorModelNumber());
923         cvfc.setToscaResourceName(buildNestedToscaResourceName(ResourceTypeEnum.VF.name(), csarInfo.getVfResourceName(), nodeName).getLeft());
924         cvfc.setInvariantUUID(UniqueIdBuilder.buildInvariantUUID());
925         List<String> tags = new ArrayList<>();
926         tags.add(cvfc.getName());
927         cvfc.setTags(tags);
928         CategoryDefinition category = new CategoryDefinition();
929         category.setName(ImportUtils.Constants.ABSTRACT_CATEGORY_NAME);
930         SubCategoryDefinition subCategory = new SubCategoryDefinition();
931         subCategory.setName(ImportUtils.Constants.ABSTRACT_SUBCATEGORY);
932         category.addSubCategory(subCategory);
933         List<CategoryDefinition> categories = new ArrayList<>();
934         categories.add(category);
935         cvfc.setCategories(categories);
936         cvfc.setVersion(ImportUtils.Constants.FIRST_NON_CERTIFIED_VERSION);
937         cvfc.setLifecycleState(ImportUtils.Constants.NORMATIVE_TYPE_LIFE_CYCLE_NOT_CERTIFIED_CHECKOUT);
938         cvfc.setHighestVersion(ImportUtils.Constants.NORMATIVE_TYPE_HIGHEST_VERSION);
939         return cvfc;
940     }
941
942     private String buildCvfcName(String resourceVfName, String nodeName) {
943         String nameWithouNamespacePrefix = nodeName.substring(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX.length());
944         String[] findTypes = nameWithouNamespacePrefix.split("\\.");
945         String resourceType = findTypes[0];
946         String resourceName = resourceVfName + "-" + nameWithouNamespacePrefix.substring(resourceType.length() + 1);
947         return addCvfcSuffixToResourceName(resourceName);
948     }
949
950     private String addCvfcSuffixToResourceName(String resourceName) {
951         return resourceName + "VF";
952     }
953
954     public UploadResourceInfo fillResourceMetadata(String yamlName, Resource resourceVf, String nodeName, User user) {
955         UploadResourceInfo resourceMetaData = new UploadResourceInfo();
956         // validate nodetype name prefix
957         if (!nodeName.startsWith(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX)) {
958             log.debug("invalid nodeName:{} does not start with {}.", nodeName, Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX);
959             throw new ComponentException(ActionStatus.INVALID_NODE_TEMPLATE, yamlName, resourceMetaData.getName(), nodeName);
960         }
961         String actualName = this.getNodeTypeActualName(nodeName);
962         String namePrefix = nodeName.replace(actualName, "");
963         String resourceType = namePrefix.substring(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX.length());
964         // if we import from csar, the node_type name can be
965
966         // org.openecomp.resource.abstract.node_name - in this case we always
967
968         // create a vfc
969         if (resourceType.equals(Constants.ABSTRACT)) {
970             resourceType = ResourceTypeEnum.VFC.name().toLowerCase();
971         }
972         // validating type
973         if (!ResourceTypeEnum.containsName(resourceType.toUpperCase())) {
974             log.debug("invalid resourceType:{} the type is not one of the valide types:{}.", resourceType.toUpperCase(), ResourceTypeEnum.values());
975             throw new ComponentException(ActionStatus.INVALID_NODE_TEMPLATE, yamlName, resourceMetaData.getName(), nodeName);
976         }
977         // Setting name
978         resourceMetaData.setName(resourceVf.getSystemName() + actualName);
979         // Setting type from name
980         String type = resourceType.toUpperCase();
981         resourceMetaData.setResourceType(type);
982         resourceMetaData.setDescription(ImportUtils.Constants.INNER_VFC_DESCRIPTION);
983         resourceMetaData.setIcon(ImportUtils.Constants.DEFAULT_ICON);
984         resourceMetaData.setContactId(user.getUserId());
985         resourceMetaData.setVendorName(resourceVf.getVendorName());
986         resourceMetaData.setTenant(resourceVf.getTenant());
987         resourceMetaData.setVendorRelease(resourceVf.getVendorRelease());
988         // Setting tag
989         List<String> tags = new ArrayList<>();
990         tags.add(resourceMetaData.getName());
991         resourceMetaData.setTags(tags);
992         // Setting category
993         CategoryDefinition category = new CategoryDefinition();
994         category.setName(ImportUtils.Constants.ABSTRACT_CATEGORY_NAME);
995         SubCategoryDefinition subCategory = new SubCategoryDefinition();
996         subCategory.setName(ImportUtils.Constants.ABSTRACT_SUBCATEGORY);
997         category.addSubCategory(subCategory);
998         List<CategoryDefinition> categories = new ArrayList<>();
999         categories.add(category);
1000         resourceMetaData.setCategories(categories);
1001         return resourceMetaData;
1002     }
1003
1004     protected String getNodeTypeActualName(String fullName) {
1005         String nameWithouNamespacePrefix = fullName.substring(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX.length());
1006         String[] findTypes = nameWithouNamespacePrefix.split("\\.");
1007         String resourceType = findTypes[0];
1008         return nameWithouNamespacePrefix.substring(resourceType.length());
1009     }
1010
1011     public void addInput(Map<String, InputDefinition> currPropertiesMap, InputDefinition prop) {
1012         String propName = prop.getName();
1013         if (!currPropertiesMap.containsKey(propName)) {
1014             currPropertiesMap.put(propName, prop);
1015         }
1016     }
1017
1018     public Either<RequirementDefinition, ResponseFormat> findAvailableRequirement(String regName, String yamlName,
1019                                                                                   UploadComponentInstanceInfo uploadComponentInstanceInfo,
1020                                                                                   ComponentInstance currentCompInstance, String capName) {
1021         Map<String, List<RequirementDefinition>> comInstRegDefMap = currentCompInstance.getRequirements();
1022         List<RequirementDefinition> list = comInstRegDefMap.get(capName);
1023         RequirementDefinition validRegDef = null;
1024         if (list == null) {
1025             for (Map.Entry<String, List<RequirementDefinition>> entry : comInstRegDefMap.entrySet()) {
1026                 for (RequirementDefinition reqDef : entry.getValue()) {
1027                     if (reqDef.getName().equals(regName)) {
1028                         if (reqDef.getMaxOccurrences() != null && !reqDef.getMaxOccurrences().equals(RequirementDataDefinition.MAX_OCCURRENCES)) {
1029                             String leftOccurrences = reqDef.getLeftOccurrences();
1030                             if (leftOccurrences == null) {
1031                                 leftOccurrences = reqDef.getMaxOccurrences();
1032                             }
1033                             int left = Integer.parseInt(leftOccurrences);
1034                             if (left > 0) {
1035                                 --left;
1036                                 reqDef.setLeftOccurrences(String.valueOf(left));
1037                                 validRegDef = reqDef;
1038                                 break;
1039                             }
1040                         } else {
1041                             validRegDef = reqDef;
1042                             break;
1043                         }
1044                     }
1045                 }
1046                 if (validRegDef != null) {
1047                     break;
1048                 }
1049             }
1050         } else {
1051             for (RequirementDefinition reqDef : list) {
1052                 if (reqDef.getName().equals(regName)) {
1053                     if (reqDef.getMaxOccurrences() != null && !reqDef.getMaxOccurrences().equals(RequirementDataDefinition.MAX_OCCURRENCES)) {
1054                         String leftOccurrences = reqDef.getLeftOccurrences();
1055                         if (leftOccurrences == null) {
1056                             leftOccurrences = reqDef.getMaxOccurrences();
1057                         }
1058                         int left = Integer.parseInt(leftOccurrences);
1059                         if (left > 0) {
1060                             --left;
1061                             reqDef.setLeftOccurrences(String.valueOf(left));
1062                             validRegDef = reqDef;
1063                             break;
1064                         }
1065                     } else {
1066                         validRegDef = reqDef;
1067                         break;
1068                     }
1069                 }
1070             }
1071         }
1072         if (validRegDef == null) {
1073             ResponseFormat responseFormat = componentsUtils
1074                 .getResponseFormat(ActionStatus.INVALID_NODE_TEMPLATE, yamlName, uploadComponentInstanceInfo.getName(),
1075                     uploadComponentInstanceInfo.getType());
1076             return Either.right(responseFormat);
1077         }
1078         return Either.left(validRegDef);
1079     }
1080
1081     public CapabilityDefinition findAvailableCapabilityByTypeOrName(RequirementDefinition validReq, ComponentInstance currentCapCompInstance,
1082                                                                     UploadReqInfo uploadReqInfo) {
1083         try {
1084             if (null == uploadReqInfo.getCapabilityName() || validReq.getCapability().equals(uploadReqInfo.getCapabilityName())) {
1085                 // get by capability type
1086                 return findAvailableCapability(validReq, currentCapCompInstance);
1087             }
1088             return findAvailableCapability(validReq, currentCapCompInstance, uploadReqInfo);
1089         } catch (Exception e) {
1090             log.debug("Exception occured when findAvailableCapabilityByTypeOrName, error is:{}", e.getMessage(), e);
1091             throw new ComponentException(ActionStatus.GENERAL_ERROR);
1092         }
1093     }
1094
1095     protected CapabilityDefinition findAvailableCapability(RequirementDefinition validReq, ComponentInstance instance) {
1096         Map<String, List<CapabilityDefinition>> capMap = instance.getCapabilities();
1097         if (capMap.containsKey(validReq.getCapability())) {
1098             List<CapabilityDefinition> capList = capMap.get(validReq.getCapability());
1099             for (CapabilityDefinition cap : capList) {
1100                 if (isBoundedByOccurrences(cap)) {
1101                     String leftOccurrences = cap.getLeftOccurrences() != null ? cap.getLeftOccurrences() : cap.getMaxOccurrences();
1102                     int left = Integer.parseInt(leftOccurrences);
1103                     if (left > 0) {
1104                         --left;
1105                         cap.setLeftOccurrences(String.valueOf(left));
1106                         return cap;
1107                     }
1108                 } else {
1109                     return cap;
1110                 }
1111             }
1112         }
1113         return null;
1114     }
1115
1116     protected CapabilityDefinition findAvailableCapability(RequirementDefinition validReq, ComponentInstance currentCapCompInstance,
1117                                                            UploadReqInfo uploadReqInfo) {
1118         CapabilityDefinition cap = null;
1119         Map<String, List<CapabilityDefinition>> capMap = currentCapCompInstance.getCapabilities();
1120         if (!capMap.containsKey(validReq.getCapability())) {
1121             return null;
1122         }
1123         Optional<CapabilityDefinition> capByName = capMap.get(validReq.getCapability()).stream()
1124             .filter(p -> p.getName().equals(uploadReqInfo.getCapabilityName())).findAny();
1125         if (!capByName.isPresent()) {
1126             return null;
1127         }
1128         cap = capByName.get();
1129         if (isBoundedByOccurrences(cap)) {
1130             String leftOccurrences = cap.getLeftOccurrences();
1131             int left = Integer.parseInt(leftOccurrences);
1132             if (left > 0) {
1133                 --left;
1134                 cap.setLeftOccurrences(String.valueOf(left));
1135             }
1136         }
1137         return cap;
1138     }
1139
1140     private boolean isBoundedByOccurrences(CapabilityDefinition cap) {
1141         return cap.getMaxOccurrences() != null && !cap.getMaxOccurrences().equals(CapabilityDataDefinition.MAX_OCCURRENCES);
1142     }
1143
1144     public ComponentParametersView getComponentFilterAfterCreateRelations() {
1145         ComponentParametersView parametersView = new ComponentParametersView();
1146         parametersView.disableAll();
1147         parametersView.setIgnoreComponentInstances(false);
1148         parametersView.setIgnoreComponentInstancesProperties(false);
1149         parametersView.setIgnoreCapabilities(false);
1150         parametersView.setIgnoreRequirements(false);
1151         parametersView.setIgnoreGroups(false);
1152         return parametersView;
1153     }
1154
1155     public ComponentParametersView getComponentWithInstancesFilter() {
1156         ComponentParametersView parametersView = new ComponentParametersView();
1157         parametersView.disableAll();
1158         parametersView.setIgnoreComponentInstances(false);
1159         parametersView.setIgnoreInputs(false);
1160         // inputs are read when creating
1161
1162         // property values on instances
1163         parametersView.setIgnoreUsers(false);
1164         return parametersView;
1165     }
1166
1167     protected void addValidComponentInstanceCapabilities(String key, List<UploadCapInfo> capabilities, String resourceId,
1168                                                          Map<String, List<CapabilityDefinition>> defaultCapabilities,
1169                                                          Map<String, List<CapabilityDefinition>> validCapabilitiesMap) {
1170         String capabilityType = capabilities.get(0).getType();
1171         if (defaultCapabilities.containsKey(capabilityType)) {
1172             CapabilityDefinition defaultCapability = getCapability(resourceId, defaultCapabilities, capabilityType);
1173             validateCapabilityProperties(capabilities, resourceId, defaultCapability);
1174             List<CapabilityDefinition> validCapabilityList = new ArrayList<>();
1175             validCapabilityList.add(defaultCapability);
1176             validCapabilitiesMap.put(key, validCapabilityList);
1177         } else {
1178             throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.MISSING_CAPABILITY_TYPE, capabilityType));
1179         }
1180     }
1181
1182     protected CapabilityDefinition getCapability(String resourceId, Map<String, List<CapabilityDefinition>> defaultCapabilities,
1183                                                  String capabilityType) {
1184         CapabilityDefinition defaultCapability;
1185         if (isNotEmpty(defaultCapabilities.get(capabilityType).get(0).getProperties())) {
1186             defaultCapability = defaultCapabilities.get(capabilityType).get(0);
1187         } else {
1188             Either<Component, StorageOperationStatus> getFullComponentRes = toscaOperationFacade.getToscaFullElement(resourceId);
1189             if (getFullComponentRes.isRight()) {
1190                 log.debug("Failed to get full component {}. Status is {}. ", resourceId, getFullComponentRes.right().value());
1191                 throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_NOT_FOUND, resourceId));
1192             }
1193             defaultCapability = getFullComponentRes.left().value().getCapabilities().get(capabilityType).get(0);
1194         }
1195         return defaultCapability;
1196     }
1197
1198     protected void validateCapabilityProperties(List<UploadCapInfo> capabilities, String resourceId, CapabilityDefinition defaultCapability) {
1199         if (CollectionUtils.isEmpty(defaultCapability.getProperties()) && isNotEmpty(capabilities.get(0).getProperties())) {
1200             log.debug("Failed to validate capability {} of component {}. Property list is empty. ", defaultCapability.getName(), resourceId);
1201             log.debug("Failed to update capability property values. Property list of fetched capability {} is empty. ", defaultCapability.getName());
1202             throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND, resourceId));
1203         } else if (isNotEmpty(capabilities.get(0).getProperties())) {
1204             validateUniquenessUpdateUploadedComponentInstanceCapability(defaultCapability, capabilities.get(0));
1205         }
1206     }
1207
1208     protected void validateUniquenessUpdateUploadedComponentInstanceCapability(CapabilityDefinition defaultCapability,
1209                                                                                UploadCapInfo uploadedCapability) {
1210         List<ComponentInstanceProperty> validProperties = new ArrayList<>();
1211         Map<String, PropertyDefinition> defaultProperties = defaultCapability.getProperties().stream()
1212             .collect(toMap(PropertyDefinition::getName, Function.identity()));
1213         List<UploadPropInfo> uploadedProperties = uploadedCapability.getProperties();
1214         for (UploadPropInfo property : uploadedProperties) {
1215             String propertyName = property.getName().toLowerCase();
1216             String propertyType = property.getType();
1217             ComponentInstanceProperty validProperty;
1218             if (defaultProperties.containsKey(propertyName) && propertyTypeEqualsTo(defaultProperties, propertyName, propertyType)) {
1219                 throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NAME_ALREADY_EXISTS, propertyName));
1220             }
1221             validProperty = new ComponentInstanceProperty();
1222             validProperty.setName(propertyName);
1223             if (property.getValue() != null) {
1224                 validProperty.setValue(property.getValue().toString());
1225             }
1226             validProperty.setDescription(property.getDescription());
1227             validProperty.setPassword(property.isPassword());
1228             validProperties.add(validProperty);
1229         }
1230         defaultCapability.setProperties(validProperties);
1231     }
1232
1233     private boolean propertyTypeEqualsTo(Map<String, PropertyDefinition> defaultProperties, String propertyName, String propertyType) {
1234         return propertyType != null && !defaultProperties.get(propertyName).getType().equals(propertyType);
1235     }
1236
1237     public void setDeploymentArtifactsPlaceHolder(Component component, User user) {
1238         if (component instanceof Service) {
1239             Service service = (Service) component;
1240             Map<String, ArtifactDefinition> artifactMap = service.getDeploymentArtifacts();
1241             if (artifactMap == null) {
1242                 artifactMap = new HashMap<>();
1243             }
1244             service.setDeploymentArtifacts(artifactMap);
1245         } else if (component instanceof Resource) {
1246             Resource resource = (Resource) component;
1247             Map<String, ArtifactDefinition> artifactMap = resource.getDeploymentArtifacts();
1248             if (artifactMap == null) {
1249                 artifactMap = new HashMap<>();
1250             }
1251             Map<String, Object> deploymentResourceArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration()
1252                 .getDeploymentResourceArtifacts();
1253             if (deploymentResourceArtifacts != null) {
1254                 Map<String, ArtifactDefinition> finalArtifactMap = artifactMap;
1255                 deploymentResourceArtifacts.forEach((k, v) -> processDeploymentResourceArtifacts(user, resource, finalArtifactMap, k, v));
1256             }
1257             resource.setDeploymentArtifacts(artifactMap);
1258         }
1259     }
1260
1261     protected void processDeploymentResourceArtifacts(User user, Resource resource, Map<String, ArtifactDefinition> artifactMap, String k, Object v) {
1262         boolean shouldCreateArtifact = true;
1263         Map<String, Object> artifactDetails = (Map<String, Object>) v;
1264         Object object = artifactDetails.get(PLACE_HOLDER_RESOURCE_TYPES);
1265         if (object != null) {
1266             List<String> artifactTypes = (List<String>) object;
1267             if (!artifactTypes.contains(resource.getResourceType().name())) {
1268                 return;
1269             }
1270         } else {
1271             log.info("resource types for artifact placeholder {} were not defined. default is all resources", k);
1272         }
1273         if (shouldCreateArtifact) {
1274             if (serviceBusinessLogic.artifactsBusinessLogic != null) {
1275                 ArtifactDefinition artifactDefinition = serviceBusinessLogic.artifactsBusinessLogic
1276                     .createArtifactPlaceHolderInfo(resource.getUniqueId(), k, (Map<String, Object>) v, user, ArtifactGroupTypeEnum.DEPLOYMENT);
1277                 if (artifactDefinition != null && !artifactMap.containsKey(artifactDefinition.getArtifactLabel())) {
1278                     artifactMap.put(artifactDefinition.getArtifactLabel(), artifactDefinition);
1279                 }
1280             }
1281         }
1282     }
1283
1284     public void mergeOldResourceMetadataWithNew(Resource oldResource, Resource newResource) {
1285         if (newResource.getTags() == null || newResource.getTags().isEmpty()) {
1286             newResource.setTags(oldResource.getTags());
1287         }
1288         if (newResource.getDescription() == null) {
1289             newResource.setDescription(oldResource.getDescription());
1290         }
1291         if (newResource.getContactId() == null) {
1292             newResource.setContactId(oldResource.getContactId());
1293         }
1294         newResource.setCategories(oldResource.getCategories());
1295     }
1296
1297     protected Resource buildComplexVfcMetadata(CsarInfo csarInfo, String nodeName, Map<String, NodeTypeInfo> nodesInfo) {
1298         Resource cvfc = new Resource();
1299         NodeTypeInfo nodeTypeInfo = nodesInfo.get(nodeName);
1300         cvfc.setName(buildCvfcName(csarInfo.getVfResourceName(), nodeName));
1301         cvfc.setNormalizedName(ValidationUtils.normaliseComponentName(cvfc.getName()));
1302         cvfc.setSystemName(ValidationUtils.convertToSystemName(cvfc.getName()));
1303         cvfc.setResourceType(ResourceTypeEnum.VF);
1304         cvfc.setAbstract(true);
1305         cvfc.setDerivedFrom(nodeTypeInfo.getDerivedFrom());
1306         cvfc.setDescription(ImportUtils.Constants.VF_DESCRIPTION);
1307         cvfc.setIcon(ImportUtils.Constants.DEFAULT_ICON);
1308         cvfc.setContactId(csarInfo.getModifier().getUserId());
1309         cvfc.setCreatorUserId(csarInfo.getModifier().getUserId());
1310         cvfc.setVendorName("cmri");
1311         cvfc.setTenant("tenant");
1312         cvfc.setVendorRelease("1.0");
1313         cvfc.setResourceVendorModelNumber("");
1314         cvfc.setToscaResourceName(buildNestedToscaResourceName(ResourceTypeEnum.VF.name(), csarInfo.getVfResourceName(), nodeName).getLeft());
1315         cvfc.setInvariantUUID(UniqueIdBuilder.buildInvariantUUID());
1316         List<String> tags = new ArrayList<>();
1317         tags.add(cvfc.getName());
1318         cvfc.setTags(tags);
1319         CategoryDefinition category = new CategoryDefinition();
1320         category.setName(ImportUtils.Constants.ABSTRACT_CATEGORY_NAME);
1321         SubCategoryDefinition subCategory = new SubCategoryDefinition();
1322         subCategory.setName(ImportUtils.Constants.ABSTRACT_SUBCATEGORY);
1323         category.addSubCategory(subCategory);
1324         List<CategoryDefinition> categories = new ArrayList<>();
1325         categories.add(category);
1326         cvfc.setCategories(categories);
1327         cvfc.setVersion(ImportUtils.Constants.FIRST_NON_CERTIFIED_VERSION);
1328         cvfc.setLifecycleState(ImportUtils.Constants.NORMATIVE_TYPE_LIFE_CYCLE_NOT_CERTIFIED_CHECKOUT);
1329         cvfc.setHighestVersion(ImportUtils.Constants.NORMATIVE_TYPE_HIGHEST_VERSION);
1330         return cvfc;
1331     }
1332
1333     public Boolean validateResourceCreationFromNodeType(Resource resource, User creator) {
1334         validateDerivedFromNotEmpty(creator, resource, AuditingActionEnum.CREATE_RESOURCE);
1335         return true;
1336     }
1337
1338     private void validateDerivedFromNotEmpty(User user, Resource resource, AuditingActionEnum actionEnum) {
1339         log.debug("validate resource derivedFrom field");
1340         if ((resource.getDerivedFrom() == null) || (resource.getDerivedFrom().isEmpty()) || (resource.getDerivedFrom().get(0)) == null || (resource
1341             .getDerivedFrom().get(0).trim().isEmpty())) {
1342             log.info("derived from (template) field is missing for the resource");
1343             ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_DERIVED_FROM_TEMPLATE);
1344             componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
1345             throw new ComponentException(ActionStatus.MISSING_DERIVED_FROM_TEMPLATE);
1346         }
1347     }
1348
1349     public Service createInputsOnService(Service service, Map<String, InputDefinition> inputs) {
1350         List<InputDefinition> resourceProperties = service.getInputs();
1351         if (MapUtils.isNotEmpty(inputs) || isNotEmpty(resourceProperties)) {
1352             Either<List<InputDefinition>, ResponseFormat> createInputs = inputsBusinessLogic.createInputsInGraph(inputs, service);
1353             if (createInputs.isRight()) {
1354                 throw new ComponentException(createInputs.right().value());
1355             }
1356         } else {
1357             return service;
1358         }
1359         Either<Service, StorageOperationStatus> updatedResource = toscaOperationFacade.getToscaElement(service.getUniqueId());
1360         if (updatedResource.isRight()) {
1361             throw new ComponentException(componentsUtils
1362                 .getResponseFormatByComponent(componentsUtils.convertFromStorageResponse(updatedResource.right().value()), service,
1363                     ComponentTypeEnum.SERVICE));
1364         }
1365         return updatedResource.left().value();
1366     }
1367
1368     public Service createOutputsOnService(final Service service, final Map<String, OutputDefinition> outputs, final String userId) {
1369         if (MapUtils.isNotEmpty(outputs) || isNotEmpty(service.getOutputs())) {
1370             final Either<List<OutputDefinition>, ResponseFormat> createOutputs = outputsBusinessLogic.createOutputsInGraph(outputs, service, userId);
1371             if (createOutputs.isRight()) {
1372                 throw new ComponentException(createOutputs.right().value());
1373             }
1374         } else {
1375             return service;
1376         }
1377         final Either<Service, StorageOperationStatus> updatedResource = toscaOperationFacade.getToscaElement(service.getUniqueId());
1378         if (updatedResource.isRight()) {
1379             throw new ComponentException(
1380                 componentsUtils.getResponseFormatByComponent(componentsUtils.convertFromStorageResponse(updatedResource.right().value()), service,
1381                     ComponentTypeEnum.SERVICE));
1382         }
1383         return updatedResource.left().value();
1384     }
1385
1386     public Service createSubstitutionFilterOnService(Service service,
1387                                                      ListDataDefinition<SubstitutionFilterPropertyDataDefinition> substitutionFilterProperties)
1388         throws BusinessLogicException {
1389         if (substitutionFilterProperties == null || substitutionFilterProperties.isEmpty()) {
1390             return service;
1391         }
1392         substitutionFilterBusinessLogic.addSubstitutionFilterInGraph(service.getUniqueId(), substitutionFilterProperties);
1393         Either<Service, StorageOperationStatus> updatedResource = toscaOperationFacade.getToscaElement(service.getUniqueId());
1394         if (updatedResource.isRight()) {
1395             throw new ComponentException(componentsUtils
1396                 .getResponseFormatByComponent(componentsUtils.convertFromStorageResponse(updatedResource.right().value()), service,
1397                     ComponentTypeEnum.SERVICE));
1398         }
1399         return updatedResource.left().value();
1400     }
1401
1402
1403     public Service createServiceTransaction(Service service, User user, boolean isNormative, AuditingActionEnum auditingAction) {
1404         if (!AuditingActionEnum.UPDATE_SERVICE_TOSCA_TEMPLATE.equals(auditingAction) &&
1405             !AuditingActionEnum.UPDATE_SERVICE_TOSCA_MODEL.equals(auditingAction)) {
1406             // validate resource name uniqueness
1407             log.debug("validate resource name");
1408             Either<Boolean, StorageOperationStatus> eitherValidation = toscaOperationFacade
1409                 .validateComponentNameExists(service.getName(), null, service.getComponentType());
1410             if (eitherValidation.isRight()) {
1411                 log.debug("Failed to validate component name {}. Status is {}. ", service.getName(), eitherValidation.right().value());
1412                 ResponseFormat errorResponse = componentsUtils
1413                     .getResponseFormat(componentsUtils.convertFromStorageResponse(eitherValidation.right().value()));
1414                 throw new ComponentException(errorResponse);
1415             }
1416             if (eitherValidation.left().value()) {
1417                 log.debug("resource with name: {}, already exists", service.getName());
1418                 ResponseFormat errorResponse = componentsUtils
1419                     .getResponseFormat(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, ComponentTypeEnum.RESOURCE.getValue(), service.getName());
1420                 throw new ComponentException(errorResponse);
1421             }
1422         }
1423         log.debug("send resource {} to dao for create", service.getName());
1424         createArtifactsPlaceHolderData(service, user);
1425         // enrich object
1426         if (!isNormative && !AuditingActionEnum.UPDATE_SERVICE_TOSCA_TEMPLATE.equals(auditingAction) &&
1427             !AuditingActionEnum.UPDATE_SERVICE_TOSCA_MODEL.equals(auditingAction)) {
1428             log.debug("enrich resource with creator, version and state");
1429             service.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
1430             service.setVersion(INITIAL_VERSION);
1431             service.setHighestVersion(true);
1432         }
1433         if (AuditingActionEnum.UPDATE_SERVICE_TOSCA_TEMPLATE.equals(auditingAction) ||
1434             AuditingActionEnum.UPDATE_SERVICE_TOSCA_MODEL.equals(auditingAction)) {
1435             toscaOperationFacade.deleteService(service.getInvariantUUID(), false);
1436         }
1437         return toscaOperationFacade.createToscaComponent(service).left().on(r -> throwComponentExceptionByResource(r, service));
1438     }
1439
1440     public Service throwComponentExceptionByResource(StorageOperationStatus status, Service service) {
1441         ResponseFormat responseFormat = componentsUtils
1442             .getResponseFormatByComponent(componentsUtils.convertFromStorageResponse(status), service, ComponentTypeEnum.SERVICE);
1443         throw new ComponentException(responseFormat);
1444     }
1445
1446     protected void createArtifactsPlaceHolderData(Service service, User user) {
1447         setInformationalArtifactsPlaceHolder(service, user);
1448         serviceBusinessLogic.setDeploymentArtifactsPlaceHolder(service, user);
1449         serviceBusinessLogic.setToscaArtifactsPlaceHolders(service, user);
1450     }
1451
1452     @SuppressWarnings("unchecked")
1453     protected void setInformationalArtifactsPlaceHolder(Service service, User user) {
1454         Map<String, ArtifactDefinition> artifactMap = service.getArtifacts();
1455         if (artifactMap == null) {
1456             artifactMap = new HashMap<>();
1457         }
1458         String resourceUniqueId = service.getUniqueId();
1459         List<String> exludeResourceCategory = ConfigurationManager.getConfigurationManager().getConfiguration().getExcludeResourceCategory();
1460         List<String> exludeResourceType = ConfigurationManager.getConfigurationManager().getConfiguration().getExcludeResourceType();
1461         Map<String, Object> informationalResourceArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration()
1462             .getInformationalResourceArtifacts();
1463         List<CategoryDefinition> categories = service.getCategories();
1464         boolean isCreateArtifact = true;
1465         if (exludeResourceCategory != null) {
1466             String category = categories.get(0).getName();
1467             isCreateArtifact = exludeResourceCategory.stream().noneMatch(e -> e.equalsIgnoreCase(category));
1468         }
1469         if (informationalResourceArtifacts != null && isCreateArtifact) {
1470             Set<String> keys = informationalResourceArtifacts.keySet();
1471             for (String informationalResourceArtifactName : keys) {
1472                 Map<String, Object> artifactInfoMap = (Map<String, Object>) informationalResourceArtifacts.get(informationalResourceArtifactName);
1473                 if (serviceBusinessLogic.artifactsBusinessLogic != null) {
1474                     ArtifactDefinition artifactDefinition = serviceBusinessLogic.artifactsBusinessLogic
1475                         .createArtifactPlaceHolderInfo(resourceUniqueId, informationalResourceArtifactName, artifactInfoMap, user,
1476                             ArtifactGroupTypeEnum.INFORMATIONAL);
1477                     artifactMap.put(artifactDefinition.getArtifactLabel(), artifactDefinition);
1478                 }
1479             }
1480         }
1481         service.setArtifacts(artifactMap);
1482     }
1483
1484     public void rollback(boolean inTransaction, Service service, List<ArtifactDefinition> createdArtifacts,
1485                          List<ArtifactDefinition> nodeTypesNewCreatedArtifacts) {
1486         if (!inTransaction) {
1487             serviceBusinessLogic.janusGraphDao.rollback();
1488         }
1489         if (isNotEmpty(createdArtifacts) && isNotEmpty(nodeTypesNewCreatedArtifacts)) {
1490             createdArtifacts.addAll(nodeTypesNewCreatedArtifacts);
1491             log.debug("Found {} newly created artifacts to deleted, the component name: {}", createdArtifacts.size(), service.getName());
1492         }
1493     }
1494
1495     public Map<String, Object> getNodeTypesFromTemplate(Map<String, Object> mappedToscaTemplate) {
1496         return ImportUtils.findFirstToscaMapElement(mappedToscaTemplate, TypeUtils.ToscaTagNamesEnum.NODE_TYPES).left().orValue(HashMap::new);
1497     }
1498
1499     private Resource nodeForceCertification(Resource resource, User user, LifecycleChangeInfoWithAction lifecycleChangeInfo, boolean inTransaction,
1500                                             boolean needLock) {
1501         return lifecycleBusinessLogic.forceResourceCertification(resource, user, lifecycleChangeInfo, inTransaction, needLock);
1502     }
1503
1504     private Resource nodeFullCertification(String uniqueId, User user, LifecycleChangeInfoWithAction lifecycleChangeInfo, boolean inTransaction,
1505                                            boolean needLock) {
1506         Either<Resource, ResponseFormat> resourceResponse = lifecycleBusinessLogic
1507             .changeState(uniqueId, user, LifeCycleTransitionEnum.CERTIFY, lifecycleChangeInfo, inTransaction, needLock);
1508         if (resourceResponse.isRight()) {
1509             throw new ByResponseFormatComponentException(resourceResponse.right().value());
1510         }
1511         return resourceResponse.left().value();
1512     }
1513
1514     public Either<Boolean, ResponseFormat> validateNestedDerivedFromDuringUpdate(Resource currentResource, Resource updateInfoResource,
1515                                                                                  boolean hasBeenCertified) {
1516         List<String> currentDerivedFrom = currentResource.getDerivedFrom();
1517         List<String> updatedDerivedFrom = updateInfoResource.getDerivedFrom();
1518         if (currentDerivedFrom == null || currentDerivedFrom.isEmpty() || updatedDerivedFrom == null || updatedDerivedFrom.isEmpty()) {
1519             log.trace("Update normative types");
1520             return Either.left(true);
1521         }
1522         String derivedFromCurrent = currentDerivedFrom.get(0);
1523         String derivedFromUpdated = updatedDerivedFrom.get(0);
1524         if (!derivedFromCurrent.equals(derivedFromUpdated)) {
1525             if (!hasBeenCertified) {
1526                 validateDerivedFromExist(null, updateInfoResource, null);
1527             } else {
1528                 Either<Boolean, ResponseFormat> validateDerivedFromExtending = validateDerivedFromExtending(null, currentResource, updateInfoResource,
1529                     null);
1530                 if (validateDerivedFromExtending.isRight() || !validateDerivedFromExtending.left().value()) {
1531                     log.debug("Derived from cannot be updated if it doesnt inherits directly or extends inheritance");
1532                     return validateDerivedFromExtending;
1533                 }
1534             }
1535         }
1536         return Either.left(true);
1537     }
1538
1539     protected Either<Boolean, ResponseFormat> validateDerivedFromExtending(User user, Resource currentResource, Resource updateInfoResource,
1540                                                                            AuditingActionEnum actionEnum) {
1541         String currentTemplateName = currentResource.getDerivedFrom().get(0);
1542         String updatedTemplateName = updateInfoResource.getDerivedFrom().get(0);
1543         Either<Boolean, StorageOperationStatus> dataModelResponse = toscaOperationFacade
1544             .validateToscaResourceNameExtends(currentTemplateName, updatedTemplateName, currentResource.getModel());
1545         if (dataModelResponse.isRight()) {
1546             StorageOperationStatus storageStatus = dataModelResponse.right().value();
1547             BeEcompErrorManager.getInstance().logBeDaoSystemError("Create/Update Resource - validateDerivingFromExtendingType");
1548             ResponseFormat responseFormat = componentsUtils
1549                 .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(storageStatus), currentResource);
1550             log.trace("audit before sending response");
1551             componentsUtils.auditResource(responseFormat, user, currentResource, actionEnum);
1552             return Either.right(responseFormat);
1553         }
1554         if (!dataModelResponse.left().value()) {
1555             log.info("resource template with name {} does not inherit as original {}", updatedTemplateName, currentTemplateName);
1556             ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.PARENT_RESOURCE_DOES_NOT_EXTEND);
1557             componentsUtils.auditResource(responseFormat, user, currentResource, actionEnum);
1558             return Either.right(responseFormat);
1559         }
1560         return Either.left(true);
1561     }
1562
1563     public void validateResourceFieldsBeforeUpdate(Resource currentResource, Resource updateInfoResource, boolean inTransaction, boolean isNested) {
1564         validateFields(currentResource, updateInfoResource, inTransaction, isNested);
1565     }
1566
1567     private void validateFields(Resource currentResource, Resource updateInfoResource, boolean inTransaction, boolean isNested) {
1568         boolean hasBeenCertified = ValidationUtils.hasBeenCertified(currentResource.getVersion());
1569         log.debug("validate resource name before update");
1570         validateResourceName(currentResource, updateInfoResource, hasBeenCertified, isNested);
1571         log.debug("validate description before update");
1572         if (serviceBusinessLogic.componentDescriptionValidator != null) {
1573             serviceBusinessLogic.componentDescriptionValidator.validateAndCorrectField(null, updateInfoResource, null);
1574         }
1575         log.debug("validate icon before update");
1576         log.debug("validate tags before update");
1577         if (serviceBusinessLogic.componentTagsValidator != null) {
1578             serviceBusinessLogic.componentTagsValidator.validateAndCorrectField(null, updateInfoResource, null);
1579         }
1580         log.debug("validate vendor name before update");
1581         log.debug("validate resource vendor model number before update");
1582         log.debug("validate vendor release before update");
1583         log.debug("validate contact info before update");
1584         if (serviceBusinessLogic.componentContactIdValidator != null) {
1585             serviceBusinessLogic.componentContactIdValidator.validateAndCorrectField(null, updateInfoResource, null);
1586         }
1587         log.debug(VALIDATE_DERIVED_BEFORE_UPDATE);
1588         log.debug("validate category before update");
1589     }
1590
1591     protected void validateResourceName(Resource currentResource, Resource updateInfoResource, boolean hasBeenCertified, boolean isNested) {
1592         String resourceNameUpdated = updateInfoResource.getName();
1593         if (!isResourceNameEquals(currentResource, updateInfoResource)) {
1594             if (isNested || !hasBeenCertified) {
1595                 serviceBusinessLogic.componentNameValidator.validateAndCorrectField(null, updateInfoResource, null);
1596                 currentResource.setName(resourceNameUpdated);
1597                 currentResource.setNormalizedName(ValidationUtils.normaliseComponentName(resourceNameUpdated));
1598                 currentResource.setSystemName(ValidationUtils.convertToSystemName(resourceNameUpdated));
1599             } else {
1600                 log.info("Resource name: {}, cannot be updated once the resource has been certified once.", resourceNameUpdated);
1601                 throw new ComponentException(ActionStatus.RESOURCE_NAME_CANNOT_BE_CHANGED);
1602             }
1603         }
1604     }
1605
1606     protected boolean isResourceNameEquals(Resource currentResource, Resource updateInfoResource) {
1607         String resourceNameUpdated = updateInfoResource.getName();
1608         String resourceNameCurrent = currentResource.getName();
1609         if (resourceNameCurrent.equals(resourceNameUpdated)) {
1610             return true;
1611         }
1612         return currentResource.getResourceType().equals(ResourceTypeEnum.VF) && resourceNameUpdated
1613             .equals(addCvfcSuffixToResourceName(resourceNameCurrent));
1614     }
1615
1616     public Resource prepareResourceForUpdate(Resource oldResource, Resource newResource, User user, boolean inTransaction, boolean needLock) {
1617         if (!ComponentValidationUtils.canWorkOnResource(oldResource, user.getUserId())) {
1618             // checkout
1619             return lifecycleBusinessLogic
1620                 .changeState(oldResource.getUniqueId(), user, LifeCycleTransitionEnum.CHECKOUT, new LifecycleChangeInfoWithAction("update by import"),
1621                     inTransaction, needLock).left().on(response -> failOnChangeState(response, user, oldResource, newResource));
1622         }
1623         return oldResource;
1624     }
1625
1626     protected Resource failOnChangeState(ResponseFormat response, User user, Resource oldResource, Resource newResource) {
1627         if (response.getRequestError() != null) {
1628             log.info("resource {} cannot be updated. reason={}", oldResource.getUniqueId(), response.getFormattedMessage());
1629             componentsUtils.auditResource(response, user, newResource, AuditingActionEnum.IMPORT_RESOURCE,
1630                 ResourceVersionInfo.newBuilder().state(oldResource.getLifecycleState().name()).version(oldResource.getVersion()).build());
1631         }
1632         throw new ComponentException(response);
1633     }
1634
1635     public Resource handleResourceGenericType(Resource resource) {
1636         Resource genericResource = serviceBusinessLogic.fetchAndSetDerivedFromGenericType(resource);
1637         if (resource.shouldGenerateInputs()) {
1638             serviceBusinessLogic.generateAndAddInputsFromGenericTypeProperties(resource, genericResource);
1639         }
1640         return genericResource;
1641     }
1642
1643     public Resource createInputsOnResource(Resource resource, Map<String, InputDefinition> inputs) {
1644         List<InputDefinition> resourceProperties = resource.getInputs();
1645         if (MapUtils.isNotEmpty(inputs) || isNotEmpty(resourceProperties)) {
1646             Either<List<InputDefinition>, ResponseFormat> createInputs = inputsBusinessLogic.createInputsInGraph(inputs, resource);
1647             if (createInputs.isRight()) {
1648                 throw new ComponentException(createInputs.right().value());
1649             }
1650         } else {
1651             return resource;
1652         }
1653         Either<Resource, StorageOperationStatus> updatedResource = toscaOperationFacade.getToscaElement(resource.getUniqueId());
1654         if (updatedResource.isRight()) {
1655             throw new ComponentException(
1656                 componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(updatedResource.right().value()), resource));
1657         }
1658         return updatedResource.left().value();
1659     }
1660
1661     protected void updateOrCreateGroups(Resource resource, Map<String, GroupDefinition> groups) {
1662         List<GroupDefinition> groupsFromResource = resource.getGroups();
1663         List<GroupDefinition> groupsAsList = updateGroupsMembersUsingResource(groups, new Service());
1664         List<GroupDefinition> groupsToUpdate = new ArrayList<>();
1665         List<GroupDefinition> groupsToDelete = new ArrayList<>();
1666         List<GroupDefinition> groupsToCreate = new ArrayList<>();
1667         if (isNotEmpty(groupsFromResource)) {
1668             addGroupsToCreateOrUpdate(groupsFromResource, groupsAsList, groupsToUpdate, groupsToCreate);
1669             addGroupsToDelete(groupsFromResource, groupsAsList, groupsToDelete);
1670         } else {
1671             groupsToCreate.addAll(groupsAsList);
1672         }
1673         if (isNotEmpty(groupsToCreate)) {
1674             fillGroupsFinalFields(groupsToCreate);
1675             if (isNotEmpty(groupsFromResource)) {
1676                 groupBusinessLogic.addGroups(resource, groupsToCreate, true).left().on(serviceBusinessLogic::throwComponentException);
1677             } else {
1678                 groupBusinessLogic.createGroups(resource, groupsToCreate, true).left().on(serviceBusinessLogic::throwComponentException);
1679             }
1680         }
1681         if (isNotEmpty(groupsToDelete)) {
1682             groupBusinessLogic.deleteGroups(resource, groupsToDelete).left().on(serviceBusinessLogic::throwComponentException);
1683         }
1684         if (isNotEmpty(groupsToUpdate)) {
1685             groupBusinessLogic.updateGroups(resource, groupsToUpdate, true).left()
1686                 .on(serviceBusinessLogic::throwComponentException);
1687         }
1688     }
1689
1690     protected void addGroupsToCreateOrUpdate(List<GroupDefinition> groupsFromResource, List<GroupDefinition> groupsAsList,
1691                                              List<GroupDefinition> groupsToUpdate, List<GroupDefinition> groupsToCreate) {
1692         for (GroupDefinition group : groupsAsList) {
1693             Optional<GroupDefinition> op = groupsFromResource.stream().filter(p -> p.getInvariantName().equalsIgnoreCase(group.getInvariantName()))
1694                 .findAny();
1695             if (op.isPresent()) {
1696                 GroupDefinition groupToUpdate = op.get();
1697                 groupToUpdate.setMembers(group.getMembers());
1698                 groupToUpdate.setCapabilities(group.getCapabilities());
1699                 groupToUpdate.setProperties(group.getProperties());
1700                 groupsToUpdate.add(groupToUpdate);
1701             } else {
1702                 groupsToCreate.add(group);
1703             }
1704         }
1705     }
1706
1707     protected void addGroupsToDelete(List<GroupDefinition> groupsFromResource, List<GroupDefinition> groupsAsList,
1708                                      List<GroupDefinition> groupsToDelete) {
1709         for (GroupDefinition group : groupsFromResource) {
1710             Optional<GroupDefinition> op = groupsAsList.stream().filter(p -> p.getName().equalsIgnoreCase(group.getName())).findAny();
1711             if (!op.isPresent() && (group.getArtifacts() == null || group.getArtifacts().isEmpty())) {
1712                 groupsToDelete.add(group);
1713             }
1714         }
1715     }
1716
1717     protected List<GroupDefinition> updateGroupsMembersUsingResource(Map<String, GroupDefinition> groups, Service component) {
1718         List<GroupDefinition> result = new ArrayList<>();
1719         List<ComponentInstance> componentInstances = component.getComponentInstances();
1720         if (groups != null) {
1721             for (Map.Entry<String, GroupDefinition> entry : groups.entrySet()) {
1722                 String groupName = entry.getKey();
1723                 GroupDefinition groupDefinition = entry.getValue();
1724                 GroupDefinition updatedGroupDefinition = new GroupDefinition(groupDefinition);
1725                 updatedGroupDefinition.setMembers(null);
1726                 Map<String, String> members = groupDefinition.getMembers();
1727                 if (members != null) {
1728                     updateGroupMembers(groups, updatedGroupDefinition, component, componentInstances, groupName, members);
1729                 }
1730                 result.add(updatedGroupDefinition);
1731             }
1732         }
1733         return result;
1734     }
1735
1736     public void updateGroupMembers(Map<String, GroupDefinition> groups, GroupDefinition updatedGroupDefinition, Service component,
1737                                    List<ComponentInstance> componentInstances, String groupName, Map<String, String> members) {
1738         Set<String> compInstancesNames = members.keySet();
1739         if (CollectionUtils.isEmpty(componentInstances)) {
1740             String membersAstString = compInstancesNames.stream().collect(joining(","));
1741             log.debug("The members: {}, in group: {}, cannot be found in component {}. There are no component instances.", membersAstString,
1742                 groupName, component.getNormalizedName());
1743             throw new ComponentException(componentsUtils
1744                 .getResponseFormat(ActionStatus.GROUP_INVALID_COMPONENT_INSTANCE, membersAstString, groupName, component.getNormalizedName(),
1745                     getComponentTypeForResponse(component)));
1746         }
1747         // Find all component instances with the member names
1748         Map<String, String> memberNames = componentInstances.stream().collect(toMap(ComponentInstance::getName, ComponentInstance::getUniqueId));
1749         memberNames.putAll(groups.keySet().stream().collect(toMap(g -> g, g -> "")));
1750         Map<String, String> relevantInstances = memberNames.entrySet().stream().filter(n -> compInstancesNames.contains(n.getKey()))
1751             .collect(toMap(Map.Entry::getKey, Map.Entry::getValue));
1752         if (relevantInstances == null || relevantInstances.size() != compInstancesNames.size()) {
1753             List<String> foundMembers = new ArrayList<>();
1754             if (relevantInstances != null) {
1755                 foundMembers = relevantInstances.keySet().stream().collect(toList());
1756             }
1757             compInstancesNames.removeAll(foundMembers);
1758             String membersAstString = compInstancesNames.stream().collect(joining(","));
1759             log.debug("The members: {}, in group: {}, cannot be found in component: {}", membersAstString, groupName, component.getNormalizedName());
1760             throw new ComponentException(componentsUtils
1761                 .getResponseFormat(ActionStatus.GROUP_INVALID_COMPONENT_INSTANCE, membersAstString, groupName, component.getNormalizedName(),
1762                     getComponentTypeForResponse(component)));
1763         }
1764         updatedGroupDefinition.setMembers(relevantInstances);
1765     }
1766
1767     public ImmutablePair<Resource, ActionStatus> createResourceFromNodeType(String nodeTypeYaml, UploadResourceInfo resourceMetaData, User creator,
1768                                                                             boolean isInTransaction, boolean needLock,
1769                                                                             Map<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle,
1770                                                                             List<ArtifactDefinition> nodeTypesNewCreatedArtifacts,
1771                                                                             boolean forceCertificationAllowed, CsarInfo csarInfo, String nodeName,
1772                                                                             boolean isNested) {
1773         LifecycleChangeInfoWithAction lifecycleChangeInfo = new LifecycleChangeInfoWithAction(CERTIFICATION_ON_IMPORT,
1774             LifecycleChangeInfoWithAction.LifecycleChanceActionEnum.CREATE_FROM_CSAR);
1775         Function<Resource, Boolean> validator = resource -> validateResourceCreationFromNodeType(resource, creator);
1776         return resourceImportManager
1777             .importCertifiedResource(nodeTypeYaml, resourceMetaData, creator, validator, lifecycleChangeInfo, isInTransaction, true, needLock,
1778                 nodeTypeArtifactsToHandle, nodeTypesNewCreatedArtifacts, forceCertificationAllowed, csarInfo, nodeName, isNested, null);
1779     }
1780
1781     public ImmutablePair<Resource, ActionStatus> createNodeTypeResourceFromYaml(String yamlName, Map.Entry<String, Object> nodeNameValue, User user,
1782                                                                                 Map<String, Object> mapToConvert, Service resourceVf,
1783                                                                                 boolean needLock,
1784                                                                                 Map<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle,
1785                                                                                 List<ArtifactDefinition> nodeTypesNewCreatedArtifacts,
1786                                                                                 boolean forceCertificationAllowed, CsarInfo csarInfo,
1787                                                                                 boolean isNested) {
1788         UploadResourceInfo resourceMetaData = fillResourceMetadata(yamlName, resourceVf, nodeNameValue.getKey(), user);
1789         String singleVfcYaml = buildNodeTypeYaml(nodeNameValue, mapToConvert, resourceMetaData.getResourceType(), csarInfo);
1790         user = serviceBusinessLogic.validateUser(user, "CheckIn Resource", resourceVf, AuditingActionEnum.CHECKIN_RESOURCE, true);
1791         return createResourceFromNodeType(singleVfcYaml, resourceMetaData, user, true, needLock, nodeTypeArtifactsToHandle,
1792             nodeTypesNewCreatedArtifacts, forceCertificationAllowed, csarInfo, nodeNameValue.getKey(), isNested);
1793     }
1794
1795     protected UploadResourceInfo fillResourceMetadata(String yamlName, Service resourceVf, String nodeName, User user) {
1796         UploadResourceInfo resourceMetaData = new UploadResourceInfo();
1797         // validate nodetype name prefix
1798         if (!nodeName.startsWith(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX)) {
1799             log.debug("invalid nodeName:{} does not start with {}.", nodeName, Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX);
1800             throw new ComponentException(ActionStatus.INVALID_NODE_TEMPLATE, yamlName, resourceMetaData.getName(), nodeName);
1801         }
1802         String actualName = this.getNodeTypeActualName(nodeName);
1803         String namePrefix = nodeName.replace(actualName, "");
1804         String resourceType = namePrefix.substring(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX.length());
1805         // if we import from csar, the node_type name can be
1806
1807         // org.openecomp.resource.abstract.node_name - in this case we always
1808
1809         // create a vfc
1810         if (resourceType.equals(Constants.ABSTRACT)) {
1811             resourceType = ResourceTypeEnum.VFC.name().toLowerCase();
1812         }
1813         // validating type
1814         if (!ResourceTypeEnum.containsName(resourceType.toUpperCase())) {
1815             log.debug("invalid resourceType:{} the type is not one of the valide types:{}.", resourceType.toUpperCase(), ResourceTypeEnum.values());
1816             throw new ComponentException(ActionStatus.INVALID_NODE_TEMPLATE, yamlName, resourceMetaData.getName(), nodeName);
1817         }
1818         // Setting name
1819         resourceMetaData.setName(resourceVf.getSystemName() + actualName);
1820         // Setting type from name
1821         String type = resourceType.toUpperCase();
1822         resourceMetaData.setResourceType(type);
1823         resourceMetaData.setDescription(ImportUtils.Constants.INNER_VFC_DESCRIPTION);
1824         resourceMetaData.setIcon(ImportUtils.Constants.DEFAULT_ICON);
1825         resourceMetaData.setContactId(user.getUserId());
1826         // Setting tag
1827         List<String> tags = new ArrayList<>();
1828         tags.add(resourceMetaData.getName());
1829         resourceMetaData.setTags(tags);
1830         // Setting category
1831         CategoryDefinition category = new CategoryDefinition();
1832         category.setName(ImportUtils.Constants.ABSTRACT_CATEGORY_NAME);
1833         SubCategoryDefinition subCategory = new SubCategoryDefinition();
1834         subCategory.setName(ImportUtils.Constants.ABSTRACT_SUBCATEGORY);
1835         category.addSubCategory(subCategory);
1836         List<CategoryDefinition> categories = new ArrayList<>();
1837         categories.add(category);
1838         resourceMetaData.setCategories(categories);
1839         return resourceMetaData;
1840     }
1841
1842     public Resource propagateStateToCertified(User user, Resource resource, LifecycleChangeInfoWithAction lifecycleChangeInfo, boolean inTransaction,
1843                                               boolean needLock, boolean forceCertificationAllowed) {
1844         Either<Resource, ResponseFormat> result = null;
1845         try {
1846             if (resource.getLifecycleState() != LifecycleStateEnum.CERTIFIED && forceCertificationAllowed && lifecycleBusinessLogic
1847                 .isFirstCertification(resource.getVersion())) {
1848                 nodeForceCertification(resource, user, lifecycleChangeInfo, inTransaction, needLock);
1849             }
1850             if (resource.getLifecycleState() == LifecycleStateEnum.CERTIFIED) {
1851                 Either<ArtifactDefinition, Operation> eitherPopulated = serviceBusinessLogic
1852                     .populateToscaArtifacts(resource, user, false, inTransaction, needLock);
1853                 return resource;
1854             }
1855             return nodeFullCertification(resource.getUniqueId(), user, lifecycleChangeInfo, inTransaction, needLock);
1856         } catch (Exception e) {
1857             log.debug("The exception has occurred upon certification of resource {}. ", resource.getName(), e);
1858             throw e;
1859         } finally {
1860             if (result == null || result.isRight()) {
1861                 BeEcompErrorManager.getInstance().logBeSystemError("Change LifecycleState - Certify");
1862                 if (!inTransaction) {
1863                     serviceBusinessLogic.janusGraphDao.rollback();
1864                 }
1865             } else if (!inTransaction) {
1866                 serviceBusinessLogic.janusGraphDao.commit();
1867             }
1868         }
1869     }
1870
1871     public Resource buildValidComplexVfc(CsarInfo csarInfo, String nodeName, Map<String, NodeTypeInfo> nodesInfo) {
1872         Resource complexVfc = buildComplexVfcMetadata(csarInfo, nodeName, nodesInfo);
1873         log.debug("************* Going to validate complex VFC from yaml {}", complexVfc.getName());
1874         csarInfo.addNodeToQueue(nodeName);
1875         return validateResourceBeforeCreate(complexVfc, csarInfo.getModifier(), AuditingActionEnum.IMPORT_RESOURCE, true, csarInfo);
1876     }
1877
1878     public Resource updateGroupsOnResource(Resource resource, Map<String, GroupDefinition> groups) {
1879         if (MapUtils.isEmpty(groups)) {
1880             return resource;
1881         } else {
1882             updateOrCreateGroups(resource, groups);
1883         }
1884         Either<Resource, StorageOperationStatus> updatedResource = toscaOperationFacade.getToscaElement(resource.getUniqueId());
1885         if (updatedResource.isRight()) {
1886             throw new ComponentException(
1887                 componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(updatedResource.right().value()), resource));
1888         }
1889         return updatedResource.left().value();
1890     }
1891
1892     protected void setInformationalArtifactsPlaceHolder(Resource resource, User user) {
1893         Map<String, ArtifactDefinition> artifactMap = resource.getArtifacts();
1894         if (artifactMap == null) {
1895             artifactMap = new HashMap<>();
1896         }
1897         String resourceUniqueId = resource.getUniqueId();
1898         List<String> exludeResourceCategory = ConfigurationManager.getConfigurationManager().getConfiguration().getExcludeResourceCategory();
1899         List<String> exludeResourceType = ConfigurationManager.getConfigurationManager().getConfiguration().getExcludeResourceType();
1900         Map<String, Object> informationalResourceArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration()
1901             .getInformationalResourceArtifacts();
1902         List<CategoryDefinition> categories = resource.getCategories();
1903         boolean isCreateArtifact = true;
1904         if (exludeResourceCategory != null) {
1905             String category = categories.get(0).getName();
1906             isCreateArtifact = exludeResourceCategory.stream().noneMatch(e -> e.equalsIgnoreCase(category));
1907         }
1908         if (isCreateArtifact && exludeResourceType != null) {
1909             String resourceType = resource.getResourceType().name();
1910             isCreateArtifact = exludeResourceType.stream().noneMatch(e -> e.equalsIgnoreCase(resourceType));
1911         }
1912         if (informationalResourceArtifacts != null && isCreateArtifact) {
1913             Set<String> keys = informationalResourceArtifacts.keySet();
1914             for (String informationalResourceArtifactName : keys) {
1915                 Map<String, Object> artifactInfoMap = (Map<String, Object>) informationalResourceArtifacts.get(informationalResourceArtifactName);
1916                 if (serviceBusinessLogic.artifactsBusinessLogic != null) {
1917                     ArtifactDefinition artifactDefinition = serviceBusinessLogic.artifactsBusinessLogic
1918                         .createArtifactPlaceHolderInfo(resourceUniqueId, informationalResourceArtifactName, artifactInfoMap, user,
1919                             ArtifactGroupTypeEnum.INFORMATIONAL);
1920                     artifactMap.put(artifactDefinition.getArtifactLabel(), artifactDefinition);
1921                 }
1922             }
1923         }
1924         resource.setArtifacts(artifactMap);
1925     }
1926
1927     public void rollback(boolean inTransaction, Resource resource, List<ArtifactDefinition> createdArtifacts,
1928                          List<ArtifactDefinition> nodeTypesNewCreatedArtifacts) {
1929         if (!inTransaction) {
1930             serviceBusinessLogic.janusGraphDao.rollback();
1931         }
1932         if (isNotEmpty(createdArtifacts) && isNotEmpty(nodeTypesNewCreatedArtifacts)) {
1933             createdArtifacts.addAll(nodeTypesNewCreatedArtifacts);
1934             log.debug("Found {} newly created artifacts to deleted, the component name: {}", createdArtifacts.size(), resource.getName());
1935         }
1936     }
1937
1938     public void createArtifactsPlaceHolderData(Resource resource, User user) {
1939         setInformationalArtifactsPlaceHolder(resource, user);
1940         setDeploymentArtifactsPlaceHolder(resource, user);
1941         serviceBusinessLogic.setToscaArtifactsPlaceHolders(resource, user);
1942     }
1943
1944     public void handleGroupsProperties(Service service, Map<String, GroupDefinition> groups) {
1945         List<InputDefinition> inputs = service.getInputs();
1946         if (MapUtils.isNotEmpty(groups)) {
1947             groups.values().stream().filter(g -> isNotEmpty(g.getProperties())).flatMap(g -> g.getProperties().stream())
1948                 .forEach(p -> handleGetInputs(p, inputs));
1949         }
1950     }
1951
1952     public void handleGroupsProperties(Resource resource, Map<String, GroupDefinition> groups) {
1953         List<InputDefinition> inputs = resource.getInputs();
1954         if (MapUtils.isNotEmpty(groups)) {
1955             groups.values().stream().filter(g -> isNotEmpty(g.getProperties())).flatMap(g -> g.getProperties().stream())
1956                 .forEach(p -> handleGetInputs(p, inputs));
1957         }
1958     }
1959
1960     protected void handleGetInputs(PropertyDataDefinition property, List<InputDefinition> inputs) {
1961         if (isNotEmpty(property.getGetInputValues())) {
1962             if (inputs == null || inputs.isEmpty()) {
1963                 log.debug("Failed to add property {} to group. Inputs list is empty ", property);
1964                 serviceBusinessLogic.rollbackWithException(ActionStatus.INPUTS_NOT_FOUND,
1965                     property.getGetInputValues().stream().map(GetInputValueDataDefinition::getInputName).collect(toList()).toString());
1966             }
1967             ListIterator<GetInputValueDataDefinition> getInputValuesIter = property.getGetInputValues().listIterator();
1968             while (getInputValuesIter.hasNext()) {
1969                 GetInputValueDataDefinition getInput = getInputValuesIter.next();
1970                 InputDefinition input = findInputByName(inputs, getInput);
1971                 getInput.setInputId(input.getUniqueId());
1972                 if (getInput.getGetInputIndex() != null) {
1973                     GetInputValueDataDefinition getInputIndex = getInput.getGetInputIndex();
1974                     input = findInputByName(inputs, getInputIndex);
1975                     getInputIndex.setInputId(input.getUniqueId());
1976                     getInputValuesIter.add(getInputIndex);
1977                 }
1978             }
1979         }
1980     }
1981
1982     public InputDefinition findInputByName(List<InputDefinition> inputs, GetInputValueDataDefinition getInput) {
1983         Optional<InputDefinition> inputOpt = inputs.stream().filter(p -> p.getName().equals(getInput.getInputName())).findFirst();
1984         if (!inputOpt.isPresent()) {
1985             log.debug("#findInputByName - Failed to find the input {} ", getInput.getInputName());
1986             serviceBusinessLogic.rollbackWithException(ActionStatus.INPUTS_NOT_FOUND, getInput.getInputName());
1987         }
1988         return inputOpt.get();
1989     }
1990
1991     public void associateComponentInstancePropertiesToComponent(String yamlName, Resource resource,
1992                                                                 Map<String, List<ComponentInstanceProperty>> instProperties) {
1993         try {
1994             Either<Map<String, List<ComponentInstanceProperty>>, StorageOperationStatus> addPropToInst = toscaOperationFacade
1995                 .associateComponentInstancePropertiesToComponent(instProperties, resource.getUniqueId());
1996             if (addPropToInst.isRight()) {
1997                 log.debug("failed to associate properties of resource {} status is {}", resource.getUniqueId(), addPropToInst.right().value());
1998                 throw new ComponentException(
1999                     componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addPropToInst.right().value()), yamlName));
2000             }
2001         } catch (Exception e) {
2002             log.debug("Exception occured when findNodeTypeArtifactsToHandle, error is:{}", e.getMessage());
2003             throw new ComponentException(ActionStatus.GENERAL_ERROR);
2004         }
2005     }
2006
2007     public void associateComponentInstanceInputsToComponent(String yamlName, Resource resource,
2008                                                             Map<String, List<ComponentInstanceInput>> instInputs) {
2009         if (MapUtils.isNotEmpty(instInputs)) {
2010             Either<Map<String, List<ComponentInstanceInput>>, StorageOperationStatus> addInputToInst = toscaOperationFacade
2011                 .associateComponentInstanceInputsToComponent(instInputs, resource.getUniqueId());
2012             if (addInputToInst.isRight()) {
2013                 log.debug("failed to associate inputs value of resource {} status is {}", resource.getUniqueId(), addInputToInst.right().value());
2014                 throw new ComponentException(
2015                     componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addInputToInst.right().value()), yamlName));
2016             }
2017         }
2018     }
2019
2020     public void associateComponentInstanceInterfacesToComponent(
2021         String yamlName,
2022         Service service,
2023         Map<String, Map<String, InterfaceDefinition>> instInterfaces
2024     ) {
2025         if (MapUtils.isNotEmpty(instInterfaces)) {
2026             Either<Map<String, MapInterfaceDataDefinition>, StorageOperationStatus> addInterfaceToInst =
2027                 toscaOperationFacade
2028                     .associateComponentInstanceInterfacesToComponent(
2029                         instInterfaces,
2030                         service.getUniqueId()
2031                     );
2032             if (addInterfaceToInst.isRight()) {
2033                 log.error("failed to associate interfaces value of service {}, status is {}", service.getUniqueId(),
2034                     addInterfaceToInst.right().value());
2035                 throw new ComponentException(
2036                     componentsUtils.getResponseFormat(
2037                         componentsUtils.convertFromStorageResponse(
2038                             addInterfaceToInst.right().value()
2039                         ),
2040                         yamlName
2041                     )
2042                 );
2043             }
2044         }
2045     }
2046
2047     public void associateDeploymentArtifactsToInstances(User user, String yamlName, Resource resource,
2048                                                         Map<String, Map<String, ArtifactDefinition>> instDeploymentArtifacts) {
2049         StorageOperationStatus addArtToInst = toscaOperationFacade.associateDeploymentArtifactsToInstances(instDeploymentArtifacts, resource, user);
2050         if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
2051             log.debug("failed to associate artifact of resource {} status is {}", resource.getUniqueId(), addArtToInst);
2052             throw new ComponentException(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName));
2053         }
2054     }
2055
2056     public void associateArtifactsToInstances(String yamlName, Resource resource, Map<String, Map<String, ArtifactDefinition>> instArtifacts) {
2057         StorageOperationStatus addArtToInst;
2058         addArtToInst = toscaOperationFacade.associateArtifactsToInstances(instArtifacts, resource);
2059         if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
2060             log.debug("failed to associate artifact of resource {} status is {}", resource.getUniqueId(), addArtToInst);
2061             throw new ComponentException(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName));
2062         }
2063     }
2064
2065     public void associateOrAddCalculatedCapReq(String yamlName, Resource resource,
2066                                                Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilities,
2067                                                Map<ComponentInstance, Map<String, List<RequirementDefinition>>> instRequirements) {
2068         StorageOperationStatus addArtToInst;
2069         addArtToInst = toscaOperationFacade.associateOrAddCalculatedCapReq(instCapabilities, instRequirements, resource);
2070         if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
2071             log.debug("failed to associate cap and req of resource {} status is {}", resource.getUniqueId(), addArtToInst);
2072             throw new ComponentException(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName));
2073         }
2074     }
2075
2076     public void associateInstAttributeToComponentToInstances(String yamlName, Resource resource,
2077                                                              Map<String, List<AttributeDefinition>> instAttributes) {
2078         StorageOperationStatus addArtToInst;
2079         addArtToInst = toscaOperationFacade.associateInstAttributeToComponentToInstances(instAttributes, resource);
2080         if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
2081             log.debug("failed to associate attributes of resource {} status is {}", resource.getUniqueId(), addArtToInst);
2082             throw new ComponentException(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName));
2083         }
2084     }
2085
2086     public Resource getResourceAfterCreateRelations(Resource resource) {
2087         ComponentParametersView parametersView = getComponentFilterAfterCreateRelations();
2088         Either<Resource, StorageOperationStatus> eitherGetResource = toscaOperationFacade.getToscaElement(resource.getUniqueId(), parametersView);
2089         if (eitherGetResource.isRight()) {
2090             throwComponentExceptionByResource(eitherGetResource.right().value(), resource);
2091         }
2092         return eitherGetResource.left().value();
2093     }
2094
2095     public Resource throwComponentExceptionByResource(StorageOperationStatus status, Resource resource) {
2096         ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(status), resource);
2097         throw new ComponentException(responseFormat);
2098     }
2099
2100     public void setCapabilityNamesTypes(Map<String, List<CapabilityDefinition>> originCapabilities,
2101                                         Map<String, List<UploadCapInfo>> uploadedCapabilities) {
2102         for (Map.Entry<String, List<UploadCapInfo>> currEntry : uploadedCapabilities.entrySet()) {
2103             if (originCapabilities.containsKey(currEntry.getKey())) {
2104                 currEntry.getValue().stream().forEach(cap -> cap.setType(currEntry.getKey()));
2105             }
2106         }
2107         for (Map.Entry<String, List<CapabilityDefinition>> capabilities : originCapabilities.entrySet()) {
2108             capabilities.getValue().stream().forEach(cap -> {
2109                 if (uploadedCapabilities.containsKey(cap.getName())) {
2110                     uploadedCapabilities.get(cap.getName()).stream().forEach(c -> {
2111                         c.setName(cap.getName());
2112                         c.setType(cap.getType());
2113                     });
2114                 }
2115             });
2116         }
2117     }
2118
2119     public Map<String, List<CapabilityDefinition>> getValidComponentInstanceCapabilities(String resourceId,
2120                                                                                          Map<String, List<CapabilityDefinition>> defaultCapabilities,
2121                                                                                          Map<String, List<UploadCapInfo>> uploadedCapabilities) {
2122         Map<String, List<CapabilityDefinition>> validCapabilitiesMap = new HashMap<>();
2123         uploadedCapabilities.forEach((k, v) -> addValidComponentInstanceCapabilities(k, v, resourceId, defaultCapabilities, validCapabilitiesMap));
2124         return validCapabilitiesMap;
2125     }
2126
2127     public void associateComponentInstanceInputsToComponent(String yamlName, Service service, Map<String, List<ComponentInstanceInput>> instInputs) {
2128         if (MapUtils.isNotEmpty(instInputs)) {
2129             Either<Map<String, List<ComponentInstanceInput>>, StorageOperationStatus> addInputToInst = toscaOperationFacade
2130                 .associateComponentInstanceInputsToComponent(instInputs, service.getUniqueId());
2131             if (addInputToInst.isRight()) {
2132                 log.debug("failed to associate inputs value of resource {} status is {}", service.getUniqueId(), addInputToInst.right().value());
2133                 throw new ComponentException(
2134                     componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addInputToInst.right().value()), yamlName));
2135             }
2136         }
2137     }
2138
2139     public void associateCINodeFilterToComponent(String yamlName, Service service, Map<String, UploadNodeFilterInfo> nodeFilter) {
2140         log.trace("************* Going to associate all resource node filters {}", yamlName);
2141         if (MapUtils.isNotEmpty(nodeFilter)) {
2142             StorageOperationStatus status = componentNodeFilterBusinessLogic.associateNodeFilterToComponentInstance(service.getUniqueId(),
2143                 nodeFilter);
2144             if (status != StorageOperationStatus.OK) {
2145                 throw new ComponentException(
2146                     componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status), yamlName));
2147             }
2148         }
2149     }
2150
2151     public void associateComponentInstancePropertiesToComponent(String yamlName, Service service,
2152                                                                 Map<String, List<ComponentInstanceProperty>> instProperties) {
2153         Either<Map<String, List<ComponentInstanceProperty>>, StorageOperationStatus> addPropToInst = toscaOperationFacade
2154             .associateComponentInstancePropertiesToComponent(instProperties, service.getUniqueId());
2155         if (addPropToInst.isRight()) {
2156             throw new ComponentException(
2157                 componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addPropToInst.right().value()), yamlName));
2158         }
2159     }
2160
2161     public void associateDeploymentArtifactsToInstances(User user, String yamlName, Service resource,
2162                                                         Map<String, Map<String, ArtifactDefinition>> instDeploymentArtifacts) {
2163         StorageOperationStatus addArtToInst = toscaOperationFacade.associateDeploymentArtifactsToInstances(instDeploymentArtifacts, resource, user);
2164         if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
2165             log.debug("failed to associate artifact of resource {} status is {}", resource.getUniqueId(), addArtToInst);
2166             throw new ComponentException(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName));
2167         }
2168     }
2169
2170     public void associateArtifactsToInstances(String yamlName, Service resource, Map<String, Map<String, ArtifactDefinition>> instArtifacts) {
2171         StorageOperationStatus addArtToInst;
2172         addArtToInst = toscaOperationFacade.associateArtifactsToInstances(instArtifacts, resource);
2173         if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
2174             log.debug("failed to associate artifact of resource {} status is {}", resource.getUniqueId(), addArtToInst);
2175             throw new ComponentException(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName));
2176         }
2177     }
2178
2179     public void associateOrAddCalculatedCapReq(String yamlName, Service resource,
2180                                                Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilities,
2181                                                Map<ComponentInstance, Map<String, List<RequirementDefinition>>> instRequirements) {
2182         StorageOperationStatus addArtToInst;
2183         addArtToInst = toscaOperationFacade.associateOrAddCalculatedCapReq(instCapabilities, instRequirements, resource);
2184         log.debug("enter associateOrAddCalculatedCapReq,get instCapabilities:{},get instRequirements:{}", instCapabilities, instRequirements);
2185         if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
2186             log.debug("failed to associate cap and req of resource {} status is {}", resource.getUniqueId(), addArtToInst);
2187             throw new ComponentException(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName));
2188         }
2189     }
2190
2191     public void associateInstAttributeToComponentToInstances(String yamlName, Service resource,
2192                                                              Map<String, List<AttributeDefinition>> instAttributes) {
2193         StorageOperationStatus addArtToInst;
2194         addArtToInst = toscaOperationFacade.associateInstAttributeToComponentToInstances(instAttributes, resource);
2195         if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
2196             log.debug("failed to associate attributes of resource {} status is {}", resource.getUniqueId(), addArtToInst);
2197             throw new ComponentException(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName));
2198         }
2199     }
2200
2201     public void associateRequirementsToService(String yamlName, Service resource, Map<String, ListRequirementDataDefinition> requirements) {
2202         StorageOperationStatus addReqToService;
2203         addReqToService = toscaOperationFacade.associateRequirementsToService(requirements, resource.getUniqueId());
2204         if (addReqToService != StorageOperationStatus.OK && addReqToService != StorageOperationStatus.NOT_FOUND) {
2205             log.debug("failed to associate attributes of resource {} status is {}", resource.getUniqueId(), addReqToService);
2206             throw new ComponentException(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addReqToService), yamlName));
2207         }
2208     }
2209
2210     public void associateCapabilitiesToService(String yamlName, Service resource, Map<String, ListCapabilityDataDefinition> capabilities) {
2211         StorageOperationStatus addCapToService;
2212         addCapToService = toscaOperationFacade.associateCapabilitiesToService(capabilities, resource.getUniqueId());
2213         if (addCapToService != StorageOperationStatus.OK && addCapToService != StorageOperationStatus.NOT_FOUND) {
2214             log.debug("failed to associate attributes of resource {} status is {}", resource.getUniqueId(), addCapToService);
2215             throw new ComponentException(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addCapToService), yamlName));
2216         }
2217     }
2218
2219     public void associateResourceInstances(String yamlName, Service service, List<RequirementCapabilityRelDef> relations) {
2220         Either<List<RequirementCapabilityRelDef>, StorageOperationStatus> relationsEither = toscaOperationFacade
2221             .associateResourceInstances(service, service.getUniqueId(), relations);
2222         if (relationsEither.isRight() && relationsEither.right().value() != StorageOperationStatus.NOT_FOUND) {
2223             StorageOperationStatus status = relationsEither.right().value();
2224             log.debug("failed to associate instances of service {} status is {}", service.getUniqueId(), status);
2225             throw new ComponentException(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status), yamlName));
2226         }
2227     }
2228
2229     public void addCapabilities(Map<String, List<CapabilityDefinition>> originCapabilities, String type, List<CapabilityDefinition> capabilities) {
2230         List<CapabilityDefinition> list = capabilities.stream().map(CapabilityDefinition::new).collect(toList());
2231         originCapabilities.put(type, list);
2232     }
2233
2234     public void addCapabilitiesProperties(Map<String, Map<String, UploadPropInfo>> newPropertiesMap, List<UploadCapInfo> capabilities) {
2235         for (UploadCapInfo capability : capabilities) {
2236             if (isNotEmpty(capability.getProperties())) {
2237                 newPropertiesMap.put(capability.getName(), capability.getProperties().stream().collect(toMap(UploadInfo::getName, p -> p)));
2238             }
2239         }
2240     }
2241
2242     public Service getServiceWithGroups(String resourceId) {
2243         ComponentParametersView filter = new ComponentParametersView();
2244         filter.setIgnoreGroups(false);
2245         Either<Service, StorageOperationStatus> updatedResource = toscaOperationFacade.getToscaElement(resourceId, filter);
2246         if (updatedResource.isRight()) {
2247             serviceBusinessLogic.rollbackWithException(componentsUtils.convertFromStorageResponse(updatedResource.right().value()), resourceId);
2248         }
2249         return updatedResource.left().value();
2250     }
2251
2252     public Resource getResourceWithGroups(String resourceId) {
2253         ComponentParametersView filter = new ComponentParametersView();
2254         filter.setIgnoreGroups(false);
2255         Either<Resource, StorageOperationStatus> updatedResource = toscaOperationFacade.getToscaElement(resourceId, filter);
2256         if (updatedResource.isRight()) {
2257             serviceBusinessLogic.rollbackWithException(componentsUtils.convertFromStorageResponse(updatedResource.right().value()), resourceId);
2258         }
2259         return updatedResource.left().value();
2260     }
2261
2262     public void associateResourceInstances(String yamlName, Resource resource, List<RequirementCapabilityRelDef> relations) {
2263         Either<List<RequirementCapabilityRelDef>, StorageOperationStatus> relationsEither = toscaOperationFacade
2264             .associateResourceInstances(resource, resource.getUniqueId(), relations);
2265         if (relationsEither.isRight() && relationsEither.right().value() != StorageOperationStatus.NOT_FOUND) {
2266             StorageOperationStatus status = relationsEither.right().value();
2267             log.debug("failed to associate instances of resource {} status is {}", resource.getUniqueId(), status);
2268             throw new ComponentException(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status), yamlName));
2269         }
2270     }
2271
2272     public void addRelationsToRI(String yamlName, Resource resource, Map<String, UploadComponentInstanceInfo> uploadResInstancesMap,
2273                                  List<ComponentInstance> componentInstancesList, List<RequirementCapabilityRelDef> relations) {
2274         for (Map.Entry<String, UploadComponentInstanceInfo> entry : uploadResInstancesMap.entrySet()) {
2275             UploadComponentInstanceInfo uploadComponentInstanceInfo = entry.getValue();
2276             ComponentInstance currentCompInstance = null;
2277             for (ComponentInstance compInstance : componentInstancesList) {
2278                 if (compInstance.getName().equals(uploadComponentInstanceInfo.getName())) {
2279                     currentCompInstance = compInstance;
2280                     break;
2281                 }
2282             }
2283             if (currentCompInstance == null) {
2284                 log.debug(COMPONENT_INSTANCE_WITH_NAME_IN_RESOURCE, uploadComponentInstanceInfo.getName(), resource.getUniqueId());
2285                 BeEcompErrorManager.getInstance()
2286                     .logInternalDataError(COMPONENT_INSTANCE_WITH_NAME + uploadComponentInstanceInfo.getName() + IN_RESOURCE, resource.getUniqueId(),
2287                         BeEcompErrorManager.ErrorSeverity.ERROR);
2288                 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
2289                 throw new ComponentException(responseFormat);
2290             }
2291             ResponseFormat addRelationToRiRes = addRelationToRI(yamlName, resource, entry.getValue(), relations);
2292             if (addRelationToRiRes.getStatus() != 200) {
2293                 throw new ComponentException(addRelationToRiRes);
2294             }
2295         }
2296     }
2297
2298     protected ResponseFormat addRelationToRI(String yamlName, Resource resource, UploadComponentInstanceInfo nodesInfoValue,
2299                                              List<RequirementCapabilityRelDef> relations) {
2300         List<ComponentInstance> componentInstancesList = resource.getComponentInstances();
2301         ComponentInstance currentCompInstance = null;
2302         for (ComponentInstance compInstance : componentInstancesList) {
2303             if (compInstance.getName().equals(nodesInfoValue.getName())) {
2304                 currentCompInstance = compInstance;
2305                 break;
2306             }
2307         }
2308         if (currentCompInstance == null) {
2309             log.debug(COMPONENT_INSTANCE_WITH_NAME_IN_RESOURCE, nodesInfoValue.getName(), resource.getUniqueId());
2310             BeEcompErrorManager.getInstance()
2311                 .logInternalDataError(COMPONENT_INSTANCE_WITH_NAME + nodesInfoValue.getName() + IN_RESOURCE, resource.getUniqueId(),
2312                     BeEcompErrorManager.ErrorSeverity.ERROR);
2313             return componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
2314         }
2315         String resourceInstanceId = currentCompInstance.getUniqueId();
2316         Map<String, List<UploadReqInfo>> regMap = nodesInfoValue.getRequirements();
2317         if (regMap != null) {
2318             Iterator<Map.Entry<String, List<UploadReqInfo>>> nodesRegValue = regMap.entrySet().iterator();
2319             while (nodesRegValue.hasNext()) {
2320                 Map.Entry<String, List<UploadReqInfo>> nodesRegInfoEntry = nodesRegValue.next();
2321                 List<UploadReqInfo> uploadRegInfoList = nodesRegInfoEntry.getValue();
2322                 for (UploadReqInfo uploadRegInfo : uploadRegInfoList) {
2323                     log.debug("Going to create  relation {}", uploadRegInfo.getName());
2324                     String regName = uploadRegInfo.getName();
2325                     RequirementCapabilityRelDef regCapRelDef = new RequirementCapabilityRelDef();
2326                     regCapRelDef.setFromNode(resourceInstanceId);
2327                     log.debug("try to find available requirement {} ", regName);
2328                     Either<RequirementDefinition, ResponseFormat> eitherReqStatus = findAvailableRequirement(regName, yamlName, nodesInfoValue,
2329                         currentCompInstance, uploadRegInfo.getCapabilityName());
2330                     if (eitherReqStatus.isRight()) {
2331                         return eitherReqStatus.right().value();
2332                     }
2333                     RequirementDefinition validReq = eitherReqStatus.left().value();
2334                     List<CapabilityRequirementRelationship> reqAndRelationshipPairList = regCapRelDef.getRelationships();
2335                     if (reqAndRelationshipPairList == null) {
2336                         reqAndRelationshipPairList = new ArrayList<>();
2337                     }
2338                     RelationshipInfo reqAndRelationshipPair = new RelationshipInfo();
2339                     reqAndRelationshipPair.setRequirement(regName);
2340                     reqAndRelationshipPair.setRequirementOwnerId(validReq.getOwnerId());
2341                     reqAndRelationshipPair.setRequirementUid(validReq.getUniqueId());
2342                     RelationshipImpl relationship = new RelationshipImpl();
2343                     relationship.setType(validReq.getCapability());
2344                     reqAndRelationshipPair.setRelationships(relationship);
2345                     ComponentInstance currentCapCompInstance = null;
2346                     for (ComponentInstance compInstance : componentInstancesList) {
2347                         if (compInstance.getName().equals(uploadRegInfo.getNode())) {
2348                             currentCapCompInstance = compInstance;
2349                             break;
2350                         }
2351                     }
2352                     if (currentCapCompInstance == null) {
2353                         log.debug("The component instance  with name {} not found on resource {} ", uploadRegInfo.getNode(), resource.getUniqueId());
2354                         BeEcompErrorManager.getInstance()
2355                             .logInternalDataError(COMPONENT_INSTANCE_WITH_NAME + uploadRegInfo.getNode() + IN_RESOURCE, resource.getUniqueId(),
2356                                 BeEcompErrorManager.ErrorSeverity.ERROR);
2357                         return componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
2358                     }
2359                     regCapRelDef.setToNode(currentCapCompInstance.getUniqueId());
2360                     log.debug("try to find aviable Capability  req name is {} ", validReq.getName());
2361                     CapabilityDefinition aviableCapForRel = findAvailableCapabilityByTypeOrName(validReq, currentCapCompInstance, uploadRegInfo);
2362                     reqAndRelationshipPair.setCapability(aviableCapForRel.getName());
2363                     reqAndRelationshipPair.setCapabilityUid(aviableCapForRel.getUniqueId());
2364                     reqAndRelationshipPair.setCapabilityOwnerId(aviableCapForRel.getOwnerId());
2365                     if (aviableCapForRel == null) {
2366                         BeEcompErrorManager.getInstance().logInternalDataError(
2367                             "aviable capability was not found. req name is " + validReq.getName() + " component instance is " + currentCapCompInstance
2368                                 .getUniqueId(), resource.getUniqueId(), BeEcompErrorManager.ErrorSeverity.ERROR);
2369                         return componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
2370                     }
2371                     CapabilityRequirementRelationship capReqRel = new CapabilityRequirementRelationship();
2372                     capReqRel.setRelation(reqAndRelationshipPair);
2373                     reqAndRelationshipPairList.add(capReqRel);
2374                     regCapRelDef.setRelationships(reqAndRelationshipPairList);
2375                     relations.add(regCapRelDef);
2376                 }
2377             }
2378         } else if (resource.getResourceType() != ResourceTypeEnum.VF) {
2379             return componentsUtils.getResponseFormat(ActionStatus.OK, yamlName);
2380         }
2381         return componentsUtils.getResponseFormat(ActionStatus.OK);
2382     }
2383 }