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