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