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