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