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