Support Inputs during Import Service
[sdc.git] / catalog-be / src / main / java / org / openecomp / sdc / be / components / impl / ServiceImportBusinessLogic.java
1 /*
2  * Copyright (C) 2020 CMCC, Inc. and others. All rights reserved.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 package org.openecomp.sdc.be.components.impl;
17
18 import static java.util.stream.Collectors.joining;
19 import static java.util.stream.Collectors.toList;
20 import static java.util.stream.Collectors.toMap;
21 import static org.apache.commons.collections.CollectionUtils.isNotEmpty;
22 import static org.openecomp.sdc.be.components.impl.ImportUtils.findFirstToscaStringElement;
23 import static org.openecomp.sdc.be.components.impl.ImportUtils.getPropertyJsonStringValue;
24 import static org.openecomp.sdc.be.tosca.CsarUtils.VF_NODE_TYPE_ARTIFACTS_PATH_PATTERN;
25
26 import com.google.gson.Gson;
27 import fj.data.Either;
28 import java.util.ArrayList;
29 import java.util.Collection;
30 import java.util.Collections;
31 import java.util.EnumMap;
32 import java.util.HashMap;
33 import java.util.HashSet;
34 import java.util.Iterator;
35 import java.util.List;
36 import java.util.Map;
37 import java.util.Map.Entry;
38 import java.util.Optional;
39 import java.util.Set;
40 import java.util.concurrent.atomic.AtomicReference;
41 import java.util.regex.Pattern;
42 import lombok.Getter;
43 import lombok.Setter;
44 import org.apache.commons.collections.CollectionUtils;
45 import org.apache.commons.collections.MapUtils;
46 import org.apache.commons.lang3.StringUtils;
47 import org.apache.commons.lang3.tuple.ImmutablePair;
48 import org.json.simple.JSONObject;
49 import org.openecomp.sdc.be.components.csar.CsarArtifactsAndGroupsBusinessLogic;
50 import org.openecomp.sdc.be.components.csar.CsarBusinessLogic;
51 import org.openecomp.sdc.be.components.csar.CsarInfo;
52 import org.openecomp.sdc.be.components.csar.ServiceCsarInfo;
53 import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic.ArtifactOperationEnum;
54 import org.openecomp.sdc.be.components.impl.artifact.ArtifactOperationInfo;
55 import org.openecomp.sdc.be.components.impl.exceptions.BusinessLogicException;
56 import org.openecomp.sdc.be.components.impl.exceptions.ByResponseFormatComponentException;
57 import org.openecomp.sdc.be.components.impl.exceptions.ComponentException;
58 import org.openecomp.sdc.be.components.impl.utils.CINodeFilterUtils;
59 import org.openecomp.sdc.be.components.impl.utils.CreateServiceFromYamlParameter;
60 import org.openecomp.sdc.be.components.lifecycle.LifecycleBusinessLogic;
61 import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoWithAction;
62 import org.openecomp.sdc.be.components.merge.resource.ResourceDataMergeBusinessLogic;
63 import org.openecomp.sdc.be.config.BeEcompErrorManager;
64 import org.openecomp.sdc.be.config.ConfigurationManager;
65 import org.openecomp.sdc.be.dao.api.ActionStatus;
66 import org.openecomp.sdc.be.dao.janusgraph.JanusGraphDao;
67 import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus;
68 import org.openecomp.sdc.be.datamodel.utils.ArtifactUtils;
69 import org.openecomp.sdc.be.datatypes.elements.ComponentInstanceDataDefinition;
70 import org.openecomp.sdc.be.datatypes.elements.GetInputValueDataDefinition;
71 import org.openecomp.sdc.be.datatypes.elements.ListCapabilityDataDefinition;
72 import org.openecomp.sdc.be.datatypes.elements.ListDataDefinition;
73 import org.openecomp.sdc.be.datatypes.elements.ListRequirementDataDefinition;
74 import org.openecomp.sdc.be.datatypes.elements.OperationDataDefinition;
75 import org.openecomp.sdc.be.datatypes.elements.OperationInputDefinition;
76 import org.openecomp.sdc.be.datatypes.elements.PolicyDataDefinition;
77 import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
78 import org.openecomp.sdc.be.datatypes.elements.RequirementSubstitutionFilterPropertyDataDefinition;
79 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
80 import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
81 import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
82 import org.openecomp.sdc.be.datatypes.tosca.ToscaGetFunctionType;
83 import org.openecomp.sdc.be.impl.ComponentsUtils;
84 import org.openecomp.sdc.be.info.NodeTypeInfoToUpdateArtifacts;
85 import org.openecomp.sdc.be.model.ArtifactDefinition;
86 import org.openecomp.sdc.be.model.AttributeDefinition;
87 import org.openecomp.sdc.be.model.CapabilityDefinition;
88 import org.openecomp.sdc.be.model.CapabilityRequirementRelationship;
89 import org.openecomp.sdc.be.model.Component;
90 import org.openecomp.sdc.be.model.ComponentInstance;
91 import org.openecomp.sdc.be.model.ComponentInstanceInput;
92 import org.openecomp.sdc.be.model.ComponentInstanceProperty;
93 import org.openecomp.sdc.be.model.ComponentParametersView;
94 import org.openecomp.sdc.be.model.DataTypeDefinition;
95 import org.openecomp.sdc.be.model.DistributionStatusEnum;
96 import org.openecomp.sdc.be.model.GroupDefinition;
97 import org.openecomp.sdc.be.model.InputDefinition;
98 import org.openecomp.sdc.be.model.InterfaceDefinition;
99 import org.openecomp.sdc.be.model.LifeCycleTransitionEnum;
100 import org.openecomp.sdc.be.model.LifecycleStateEnum;
101 import org.openecomp.sdc.be.model.NodeTypeDefinition;
102 import org.openecomp.sdc.be.model.NodeTypeInfo;
103 import org.openecomp.sdc.be.model.NodeTypeMetadata;
104 import org.openecomp.sdc.be.model.NodeTypesMetadataList;
105 import org.openecomp.sdc.be.model.Operation;
106 import org.openecomp.sdc.be.model.OutputDefinition;
107 import org.openecomp.sdc.be.model.ParsedToscaYamlInfo;
108 import org.openecomp.sdc.be.model.PolicyDefinition;
109 import org.openecomp.sdc.be.model.PropertyDefinition;
110 import org.openecomp.sdc.be.model.RelationshipImpl;
111 import org.openecomp.sdc.be.model.RelationshipInfo;
112 import org.openecomp.sdc.be.model.RequirementCapabilityRelDef;
113 import org.openecomp.sdc.be.model.RequirementDefinition;
114 import org.openecomp.sdc.be.model.Resource;
115 import org.openecomp.sdc.be.model.Service;
116 import org.openecomp.sdc.be.model.UploadAttributeInfo;
117 import org.openecomp.sdc.be.model.UploadComponentInstanceInfo;
118 import org.openecomp.sdc.be.model.UploadInterfaceInfo;
119 import org.openecomp.sdc.be.model.UploadNodeFilterInfo;
120 import org.openecomp.sdc.be.model.UploadPropInfo;
121 import org.openecomp.sdc.be.model.UploadReqInfo;
122 import org.openecomp.sdc.be.model.UploadResourceInfo;
123 import org.openecomp.sdc.be.model.User;
124 import org.openecomp.sdc.be.model.cache.ApplicationDataTypeCache;
125 import org.openecomp.sdc.be.model.jsonjanusgraph.datamodel.ToscaElement;
126 import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade;
127 import org.openecomp.sdc.be.model.jsonjanusgraph.utils.ModelConverter;
128 import org.openecomp.sdc.be.model.operations.StorageException;
129 import org.openecomp.sdc.be.model.operations.api.IGraphLockOperation;
130 import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
131 import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder;
132 import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
133 import org.openecomp.sdc.be.tosca.CsarUtils;
134 import org.openecomp.sdc.be.ui.model.OperationUi;
135 import org.openecomp.sdc.be.utils.TypeUtils;
136 import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum;
137 import org.openecomp.sdc.common.api.ArtifactTypeEnum;
138 import org.openecomp.sdc.common.api.Constants;
139 import org.openecomp.sdc.common.datastructure.Wrapper;
140 import org.openecomp.sdc.common.kpi.api.ASDCKpiApi;
141 import org.openecomp.sdc.common.log.wrappers.Logger;
142 import org.openecomp.sdc.common.util.ValidationUtils;
143 import org.openecomp.sdc.exception.ResponseFormat;
144 import org.springframework.beans.factory.annotation.Autowired;
145 import org.yaml.snakeyaml.Yaml;
146
147 @Getter
148 @Setter
149 @org.springframework.stereotype.Component("serviceImportBusinessLogic")
150 public class ServiceImportBusinessLogic {
151
152     protected static final String CREATE_RESOURCE = "Create Resource";
153     private static final String INITIAL_VERSION = "0.1";
154     private static final String IN_RESOURCE = " in resource {} ";
155     private static final String COMPONENT_INSTANCE_WITH_NAME = "component instance with name ";
156     private static final String COMPONENT_INSTANCE_WITH_NAME_IN_RESOURCE = "component instance with name {}  in resource {} ";
157     private static final String CERTIFICATION_ON_IMPORT = "certification on import";
158     private static final String VALIDATE_DERIVED_BEFORE_UPDATE = "validate derived before update";
159     private static final String PLACE_HOLDER_RESOURCE_TYPES = "validForResourceTypes";
160     private static final String CREATE_RESOURCE_VALIDATE_CAPABILITY_TYPES = "Create Resource - validateCapabilityTypesCreate";
161     private static final String CATEGORY_IS_EMPTY = "Resource category is empty";
162     private static final Logger log = Logger.getLogger(ServiceImportBusinessLogic.class);
163
164     private final ComponentsUtils componentsUtils;
165     private final ToscaOperationFacade toscaOperationFacade;
166     private final ServiceBusinessLogic serviceBusinessLogic;
167     private final CsarBusinessLogic csarBusinessLogic;
168     private final CsarArtifactsAndGroupsBusinessLogic csarArtifactsAndGroupsBusinessLogic;
169     private final LifecycleBusinessLogic lifecycleBusinessLogic;
170     private final CompositionBusinessLogic compositionBusinessLogic;
171     private final ResourceDataMergeBusinessLogic resourceDataMergeBusinessLogic;
172     private final ServiceImportParseLogic serviceImportParseLogic;
173     private final GroupBusinessLogic groupBusinessLogic;
174     private final PolicyBusinessLogic policyBusinessLogic;
175     private final ResourceImportManager resourceImportManager;
176     private final JanusGraphDao janusGraphDao;
177     private final ArtifactsBusinessLogic artifactsBusinessLogic;
178     private final IGraphLockOperation graphLockOperation;
179     private final ToscaFunctionService toscaFunctionService;
180     private final DataTypeBusinessLogic dataTypeBusinessLogic;
181     private ApplicationDataTypeCache applicationDataTypeCache;
182
183     public ServiceImportBusinessLogic(final GroupBusinessLogic groupBusinessLogic, final ArtifactsBusinessLogic artifactsBusinessLogic,
184                                       final ComponentsUtils componentsUtils, final ToscaOperationFacade toscaOperationFacade,
185                                       final ServiceBusinessLogic serviceBusinessLogic, final CsarBusinessLogic csarBusinessLogic,
186                                       final CsarArtifactsAndGroupsBusinessLogic csarArtifactsAndGroupsBusinessLogic,
187                                       final LifecycleBusinessLogic lifecycleBusinessLogic, final CompositionBusinessLogic compositionBusinessLogic,
188                                       final ResourceDataMergeBusinessLogic resourceDataMergeBusinessLogic,
189                                       final ServiceImportParseLogic serviceImportParseLogic, final PolicyBusinessLogic policyBusinessLogic,
190                                       final ResourceImportManager resourceImportManager, final JanusGraphDao janusGraphDao,
191                                       final IGraphLockOperation graphLockOperation, final ToscaFunctionService toscaFunctionService,
192                                       final DataTypeBusinessLogic dataTypeBusinessLogic) {
193         this.componentsUtils = componentsUtils;
194         this.toscaOperationFacade = toscaOperationFacade;
195         this.serviceBusinessLogic = serviceBusinessLogic;
196         this.csarBusinessLogic = csarBusinessLogic;
197         this.csarArtifactsAndGroupsBusinessLogic = csarArtifactsAndGroupsBusinessLogic;
198         this.lifecycleBusinessLogic = lifecycleBusinessLogic;
199         this.compositionBusinessLogic = compositionBusinessLogic;
200         this.resourceDataMergeBusinessLogic = resourceDataMergeBusinessLogic;
201         this.serviceImportParseLogic = serviceImportParseLogic;
202         this.groupBusinessLogic = groupBusinessLogic;
203         this.policyBusinessLogic = policyBusinessLogic;
204         this.resourceImportManager = resourceImportManager;
205         this.janusGraphDao = janusGraphDao;
206         this.artifactsBusinessLogic = artifactsBusinessLogic;
207         this.graphLockOperation = graphLockOperation;
208         this.toscaFunctionService = toscaFunctionService;
209         this.dataTypeBusinessLogic = dataTypeBusinessLogic;
210     }
211
212     @Autowired
213     public void setApplicationDataTypeCache(ApplicationDataTypeCache applicationDataTypeCache) {
214         this.applicationDataTypeCache = applicationDataTypeCache;
215     }
216
217     public Service createService(Service service, AuditingActionEnum auditingAction, User user, Map<String, byte[]> csarUIPayload,
218                                  String payloadName) {
219         log.debug("enter createService");
220         service.setCreatorUserId(user.getUserId());
221         service.setState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
222         service.setVersion(INITIAL_VERSION);
223         service.setConformanceLevel(ConfigurationManager.getConfigurationManager().getConfiguration().getToscaConformanceLevel());
224         service.setDistributionStatus(DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED);
225         try {
226             final var serviceBeforeCreate = serviceBusinessLogic.validateServiceBeforeCreate(service, user, auditingAction);
227             if (serviceBeforeCreate.isRight()) {
228                 throw new ComponentException(ActionStatus.GENERAL_ERROR);
229             }
230             log.debug("enter createService,validateServiceBeforeCreate success");
231             String csarUUID = payloadName == null ? service.getCsarUUID() : payloadName;
232             log.debug("enter createService,get csarUUID:{}", csarUUID);
233             csarBusinessLogic.validateCsarBeforeCreate(service, csarUUID);
234             log.debug("CsarUUID is {} - going to create resource from CSAR", csarUUID);
235             return createServiceFromCsar(service, user, csarUIPayload, csarUUID);
236         } catch (final ComponentException e) {
237             log.debug("Exception occurred when createService: {}", e.getMessage(), e);
238             throw e;
239         } catch (final Exception e) {
240             log.debug("Exception occurred when createService: {}", e.getMessage(), e);
241             throw new ComponentException(ActionStatus.GENERAL_ERROR);
242         }
243     }
244
245     protected Service createServiceFromCsar(Service service, User user, Map<String, byte[]> csarUIPayload, String csarUUID) {
246         log.trace("************* created successfully from YAML, resource TOSCA ");
247         try {
248             ServiceCsarInfo csarInfo = csarBusinessLogic.getCsarInfo(service, null, user, csarUIPayload, csarUUID);
249
250             final Map<String, Object> dataTypesToCreate = getDatatypesToCreate(service.getModel(), csarInfo);
251             if (MapUtils.isNotEmpty(dataTypesToCreate)) {
252                 dataTypeBusinessLogic.createDataTypeFromYaml(new Yaml().dump(dataTypesToCreate), service.getModel(), true);
253             }
254             final List<NodeTypeDefinition> nodeTypesToCreate = getNodeTypesToCreate(service.getModel(), csarInfo);
255             if (CollectionUtils.isNotEmpty(nodeTypesToCreate)) {
256                 createNodeTypes(nodeTypesToCreate, csarInfo);
257             }
258             Map<String, NodeTypeInfo> nodeTypesInfo = csarInfo.extractTypesInfo();
259             Either<Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>>, ResponseFormat> findNodeTypesArtifactsToHandleRes = serviceImportParseLogic
260                 .findNodeTypesArtifactsToHandle(nodeTypesInfo, csarInfo, service);
261             if (findNodeTypesArtifactsToHandleRes.isRight()) {
262                 log.debug("failed to find node types for update with artifacts during import csar {}. ", csarInfo.getCsarUUID());
263                 throw new ComponentException(findNodeTypesArtifactsToHandleRes.right().value());
264             }
265             return createServiceFromYaml(service, csarInfo.getMainTemplateContent(), csarInfo.getMainTemplateName(), nodeTypesInfo, csarInfo,
266                 findNodeTypesArtifactsToHandleRes.left().value(), true, false, null, user.getUserId());
267         } catch (final ComponentException e) {
268             log.debug("Exception occurred when createServiceFromCsar,error is:{}", e.getMessage(), e);
269             throw e;
270         } catch (final Exception e) {
271             log.debug("Exception occurred when createServiceFromCsar,error is:{}", e.getMessage(), e);
272             throw new ComponentException(ActionStatus.GENERAL_ERROR);
273         }
274     }
275
276     private Map<String, Object> getDatatypesToCreate(final String model, final CsarInfo csarInfo) {
277         final Map<String, Object> dataTypesToCreate = new HashMap<>();
278
279         for (final Entry<String, Object> dataTypeEntry : csarInfo.getDataTypes().entrySet()) {
280             final Either<DataTypeDefinition, JanusGraphOperationStatus> result = applicationDataTypeCache.get(model,
281                 UniqueIdBuilder.buildDataTypeUid(model, dataTypeEntry.getKey()));
282             if (result.isRight() && result.right().value().equals(JanusGraphOperationStatus.NOT_FOUND)) {
283                 dataTypesToCreate.put(dataTypeEntry.getKey(), dataTypeEntry.getValue());
284                 log.info("Deploying unknown type " + dataTypeEntry.getKey() + " to model " + model + " from package " + csarInfo.getCsarUUID());
285             }
286         }
287         return dataTypesToCreate;
288     }
289
290     private void createNodeTypes(List<NodeTypeDefinition> nodeTypesToCreate, ServiceCsarInfo csarInfo) {
291         NodeTypesMetadataList nodeTypesMetadataList = new NodeTypesMetadataList();
292         List<NodeTypeMetadata> nodeTypeMetadataList = new ArrayList<>();
293
294         final Map<String, Object> allTypesToCreate = new HashMap<>();
295         nodeTypesToCreate.stream().forEach(nodeType -> {
296             allTypesToCreate.put(nodeType.getMappedNodeType().getKey(), nodeType.getMappedNodeType().getValue());
297             nodeTypeMetadataList.add(nodeType.getNodeTypeMetadata());
298         });
299
300         nodeTypesMetadataList.setNodeMetadataList(nodeTypeMetadataList);
301         resourceImportManager.importAllNormativeResource(allTypesToCreate, nodeTypesMetadataList, csarInfo.getModifier(), true, false);
302     }
303
304     private List<NodeTypeDefinition> getNodeTypesToCreate(final String model, final ServiceCsarInfo csarInfo) {
305         List<NodeTypeDefinition> namesOfNodeTypesToCreate = new ArrayList<>();
306
307         for (final NodeTypeDefinition nodeTypeDefinition : csarInfo.getNodeTypesUsed()) {
308             Either<Component, StorageOperationStatus> result = toscaOperationFacade
309                 .getLatestByToscaResourceName(nodeTypeDefinition.getMappedNodeType().getKey(), model);
310             if (result.isRight() && result.right().value().equals(StorageOperationStatus.NOT_FOUND)) {
311                 namesOfNodeTypesToCreate.add(nodeTypeDefinition);
312             }
313         }
314         return namesOfNodeTypesToCreate;
315     }
316
317     protected Service createServiceFromYaml(Service service, String topologyTemplateYaml, String yamlName, Map<String, NodeTypeInfo> nodeTypesInfo,
318                                             CsarInfo csarInfo,
319                                             Map<String, EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToCreate,
320                                             boolean shouldLock, boolean inTransaction, String nodeName, final String userId)
321         throws BusinessLogicException {
322         List<ArtifactDefinition> createdArtifacts = new ArrayList<>();
323         Service createdService;
324         CreateServiceFromYamlParameter csfyp = new CreateServiceFromYamlParameter();
325         try {
326             ParsedToscaYamlInfo parsedToscaYamlInfo = csarBusinessLogic
327                 .getParsedToscaYamlInfo(topologyTemplateYaml, yamlName, nodeTypesInfo, csarInfo, nodeName, service);
328             log.debug("#createResourceFromYaml - Going to create resource {} and RIs ", service.getName());
329             csfyp.setYamlName(yamlName);
330             csfyp.setParsedToscaYamlInfo(parsedToscaYamlInfo);
331             csfyp.setCreatedArtifacts(createdArtifacts);
332             csfyp.setTopologyTemplateYaml(topologyTemplateYaml);
333             csfyp.setNodeTypesInfo(nodeTypesInfo);
334             csfyp.setCsarInfo(csarInfo);
335             csfyp.setNodeName(nodeName);
336             createdService = createServiceAndRIsFromYaml(service, false, nodeTypesArtifactsToCreate, shouldLock, inTransaction, csfyp, userId);
337             log.debug("#createResourceFromYaml - The resource {} has been created ", service.getName());
338         } catch (ComponentException | BusinessLogicException e) {
339             log.debug("Create Service from yaml failed", e);
340             throw e;
341         } catch (StorageException e) {
342             log.debug("create Service From Yaml failed,get StorageException:{}", e);
343             throw e;
344         }
345         return createdService;
346     }
347
348     protected Service createServiceAndRIsFromYaml(Service service, boolean isNormative,
349                                                   Map<String, EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToCreate,
350                                                   boolean shouldLock, boolean inTransaction, CreateServiceFromYamlParameter csfyp,
351                                                   final String userId)
352         throws BusinessLogicException {
353         List<ArtifactDefinition> nodeTypesNewCreatedArtifacts = new ArrayList<>();
354         String yamlName = csfyp.getYamlName();
355         ParsedToscaYamlInfo parsedToscaYamlInfo = csfyp.getParsedToscaYamlInfo();
356         List<ArtifactDefinition> createdArtifacts = csfyp.getCreatedArtifacts();
357         String topologyTemplateYaml = csfyp.getTopologyTemplateYaml();
358         Map<String, NodeTypeInfo> nodeTypesInfo = csfyp.getNodeTypesInfo();
359         CsarInfo csarInfo = csfyp.getCsarInfo();
360         String nodeName = csfyp.getNodeName();
361         if (shouldLock) {
362             Either<Boolean, ResponseFormat> lockResult = serviceBusinessLogic.lockComponentByName(service.getSystemName(), service, CREATE_RESOURCE);
363             if (lockResult.isRight()) {
364                 serviceImportParseLogic.rollback(inTransaction, service, createdArtifacts, nodeTypesNewCreatedArtifacts);
365                 throw new ComponentException(lockResult.right().value());
366             }
367             log.debug("name is locked {} status = {}", service.getSystemName(), lockResult);
368         }
369         boolean rollback = false;
370         try {
371             log.trace("************* Adding properties to service from interface yaml {}", yamlName);
372             Map<String, PropertyDefinition> properties = parsedToscaYamlInfo.getProperties();
373             if (properties != null && !properties.isEmpty()) {
374                 final List<PropertyDefinition> propertiesList = new ArrayList<>();
375                 properties.forEach((propertyName, propertyDefinition) -> {
376                     propertyDefinition.setName(propertyName);
377                     propertiesList.add(propertyDefinition);
378                 });
379                 service.setProperties(propertiesList);
380             }
381             log.trace("************* createResourceFromYaml before full create resource {}", yamlName);
382             service = serviceImportParseLogic.createServiceTransaction(service, csarInfo.getModifier(), isNormative);
383             log.trace("************* Going to add inputs from yaml {}", yamlName);
384             Map<String, InputDefinition> inputs = parsedToscaYamlInfo.getInputs();
385             service = serviceImportParseLogic.createInputsOnService(service, inputs);
386             log.trace("************* Finished to add inputs from yaml {}", yamlName);
387             ListDataDefinition<RequirementSubstitutionFilterPropertyDataDefinition> substitutionFilterProperties = parsedToscaYamlInfo.getSubstitutionFilterProperties();
388             service = serviceImportParseLogic.createSubstitutionFilterOnService(service, substitutionFilterProperties);
389             log.trace("************* Added Substitution filter from interface yaml {}", yamlName);
390             Map<String, UploadComponentInstanceInfo> uploadComponentInstanceInfoMap = parsedToscaYamlInfo.getInstances();
391             log.trace("************* Going to create nodes, RI's and Relations  from yaml {}", yamlName);
392             service = createRIAndRelationsFromYaml(yamlName, service, uploadComponentInstanceInfoMap, topologyTemplateYaml,
393                 nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo, nodeTypesArtifactsToCreate, nodeName);
394             log.trace("************* Finished to create nodes, RI and Relation  from yaml {}", yamlName);
395             log.trace("************* Going to add outputs from yaml {}", yamlName);
396             Map<String, OutputDefinition> outputs = parsedToscaYamlInfo.getOutputs();
397             service = serviceImportParseLogic.createOutputsOnService(service, outputs, userId);
398             log.trace("************* Finished to add outputs from yaml {}", yamlName);
399
400             Either<Map<String, GroupDefinition>, ResponseFormat> validateUpdateVfGroupNamesRes
401                 = groupBusinessLogic.validateUpdateVfGroupNames(parsedToscaYamlInfo.getGroups(), service.getSystemName());
402             if (validateUpdateVfGroupNamesRes.isRight()) {
403                 serviceImportParseLogic.rollback(inTransaction, service, createdArtifacts, nodeTypesNewCreatedArtifacts);
404                 throw new ComponentException(validateUpdateVfGroupNamesRes.right().value());
405             }
406             Map<String, GroupDefinition> groups;
407             log.trace("************* Going to add groups from yaml {}", yamlName);
408             if (!validateUpdateVfGroupNamesRes.left().value().isEmpty()) {
409                 groups = validateUpdateVfGroupNamesRes.left().value();
410             } else {
411                 groups = parsedToscaYamlInfo.getGroups();
412             }
413             Either<Service, ResponseFormat> createGroupsOnResource = createGroupsOnResource(service, groups);
414             if (createGroupsOnResource.isRight()) {
415                 serviceImportParseLogic.rollback(inTransaction, service, createdArtifacts, nodeTypesNewCreatedArtifacts);
416                 throw new ComponentException(createGroupsOnResource.right().value());
417             }
418             service = createGroupsOnResource.left().value();
419
420             Either<Service, ResponseFormat> createPoliciesOnResource = createPoliciesOnResource(service, parsedToscaYamlInfo.getPolicies());
421             if (createPoliciesOnResource.isRight()) {
422                 serviceImportParseLogic.rollback(inTransaction, service, createdArtifacts, nodeTypesNewCreatedArtifacts);
423                 throw new ComponentException(createPoliciesOnResource.right().value());
424             }
425             service = createPoliciesOnResource.left().value();
426             log.trace("************* Going to add artifacts from yaml {}", yamlName);
427             NodeTypeInfoToUpdateArtifacts nodeTypeInfoToUpdateArtifacts = new NodeTypeInfoToUpdateArtifacts(nodeName, nodeTypesArtifactsToCreate);
428             Either<Service, ResponseFormat> createArtifactsEither = createOrUpdateArtifacts(ArtifactsBusinessLogic.ArtifactOperationEnum.CREATE,
429                 createdArtifacts, yamlName, csarInfo, service, nodeTypeInfoToUpdateArtifacts, inTransaction, shouldLock);
430             if (createArtifactsEither.isRight()) {
431                 serviceImportParseLogic.rollback(inTransaction, service, createdArtifacts, nodeTypesNewCreatedArtifacts);
432                 throw new ComponentException(createArtifactsEither.right().value());
433             }
434             service = serviceImportParseLogic.getServiceWithGroups(createArtifactsEither.left().value().getUniqueId());
435             service = updateInputs(service, userId);
436
437             ASDCKpiApi.countCreatedResourcesKPI();
438             return service;
439         } catch (ComponentException | StorageException | BusinessLogicException e) {
440             rollback = true;
441             serviceImportParseLogic.rollback(inTransaction, service, createdArtifacts, nodeTypesNewCreatedArtifacts);
442             throw e;
443         } finally {
444             if (!inTransaction) {
445                 if (rollback) {
446                     janusGraphDao.rollback();
447                 } else {
448                     janusGraphDao.commit();
449                 }
450             }
451             if (shouldLock) {
452                 graphLockOperation.unlockComponentByName(service.getSystemName(), service.getUniqueId(), NodeTypeEnum.Resource);
453             }
454         }
455     }
456
457     private Service updateInputs(final Service component, final String userId) {
458         final List<InputDefinition> inputs = component.getInputs();
459         final List<ComponentInstance> componentInstances = component.getComponentInstances();
460         final String componentUniqueId = component.getUniqueId();
461         final Map<String, List<ComponentInstanceProperty>> componentInstancesProperties = component.getComponentInstancesProperties();
462         for (final InputDefinition input : inputs) {
463             if (isInputFromComponentInstanceProperty(input.getName(), componentInstances, componentInstancesProperties)) {
464                 associateInputToComponentInstanceProperty(userId, input, componentInstances, componentInstancesProperties,
465                     componentUniqueId);
466             } else {
467                 associateInputToServiceProperty(userId, input, component);
468             }
469
470         }
471
472         final Either<List<InputDefinition>, StorageOperationStatus> either
473             = toscaOperationFacade.updateInputsToComponent(inputs, componentUniqueId);
474         if (either.isRight()) {
475             throw new ComponentException(ActionStatus.GENERAL_ERROR);
476         }
477
478         return component;
479     }
480
481     private boolean isInputFromComponentInstanceProperty(final String inputName, final List<ComponentInstance> componentInstances,
482                                                          final Map<String, List<ComponentInstanceProperty>> componentInstancesProperties) {
483         if (CollectionUtils.isNotEmpty(componentInstances)) {
484             // get instance's names
485             final List<String> componentInstancesNames = componentInstances.stream().map(ComponentInstanceDataDefinition::getNormalizedName)
486                 .collect(toList());
487             final Optional<String> componentInstancesNameOptional = componentInstancesNames.stream()
488                 .filter(cin -> inputName.startsWith(cin + "_")).findFirst();
489             if (componentInstancesNameOptional.isPresent() && MapUtils.isNotEmpty(componentInstancesProperties)) {
490                 final Optional<String> componentInstanceIdOptional = componentInstancesProperties.keySet().stream()
491                     .filter(key -> key.endsWith("." + componentInstancesNameOptional.get())).findFirst();
492                 if (componentInstanceIdOptional.isPresent()) {
493                     // get property's name
494                     final String propertyNameFromInput = extractPropertyNameFromInputName(inputName, componentInstancesNames);
495                     return componentInstancesProperties.get(componentInstanceIdOptional.get()).stream()
496                         .anyMatch(prop -> prop.getName().equals(propertyNameFromInput) && prop.getValue() != null
497                             && prop.getValue().contains(ToscaGetFunctionType.GET_INPUT.getFunctionName()));
498                 }
499             }
500         }
501         return false;
502     }
503
504     private void associateInputToComponentInstanceProperty(final String userId, final InputDefinition input,
505                                                            final List<ComponentInstance> componentInstances,
506                                                            final Map<String, List<ComponentInstanceProperty>> componentInstancesProperties,
507                                                            String componentUniqueId) {
508         // From Instance
509         final List<String> componentInstancesNames = componentInstances.stream().map(ComponentInstanceDataDefinition::getNormalizedName)
510             .collect(toList());
511         final String propertyNameFromInput = extractPropertyNameFromInputName(input.getName(), componentInstancesNames);
512
513         final Optional<String> componentInstancesNameOptional = componentInstancesNames.stream()
514             .filter(cin -> input.getName().startsWith(cin + "_")).findFirst();
515
516         final Optional<String> componentInstanceIdOptional = componentInstancesProperties.keySet().stream()
517             .filter(key -> key.endsWith("." + componentInstancesNameOptional.get())).findFirst();
518
519         final String componentInstanceId = componentInstanceIdOptional.get();
520         final List<ComponentInstanceProperty> componentInstanceProperties = componentInstancesProperties.get(componentInstanceId);
521
522         final ComponentInstanceProperty componentInstanceProperty = componentInstanceProperties.stream()
523             .filter(prop -> prop.getName().equals(propertyNameFromInput) && prop.getValue() != null
524                 && prop.getValue().contains(ToscaGetFunctionType.GET_INPUT.getFunctionName())).findFirst().get();
525
526         // From Instance
527         updateInput(input, componentInstanceProperty, userId, componentInstanceId);
528
529         final Either<Map<String, List<ComponentInstanceProperty>>, StorageOperationStatus> either =
530             toscaOperationFacade.updateComponentInstancePropsToComponent(Collections.singletonMap(componentInstanceId,
531                 Collections.singletonList(componentInstanceProperty)), componentUniqueId);
532         if (either.isRight()) {
533             throw new ComponentException(ActionStatus.GENERAL_ERROR);
534         }
535     }
536
537     private void associateInputToServiceProperty(final String userId,
538                                                  final InputDefinition input, final Service component) {
539         final List<PropertyDefinition> properties = component.getProperties();
540         if (CollectionUtils.isNotEmpty(properties)) {
541             final String propertyNameFromInput = input.getName();
542             final Optional<PropertyDefinition> propDefOptional = properties.stream().filter(prop -> prop.getName().equals(propertyNameFromInput))
543                 .findFirst();
544             if (propDefOptional.isPresent()) {
545                 // From SELF
546                 final String componentUniqueId = component.getUniqueId();
547                 final PropertyDefinition propertyDefinition = propDefOptional.get();
548                 updateProperty(propertyDefinition, input, componentUniqueId);
549                 final JSONObject jsonObject = new JSONObject();
550                 jsonObject.put(ToscaGetFunctionType.GET_INPUT.getFunctionName(), input.getName());
551                 propertyDefinition.setValue(jsonObject.toJSONString());
552                 updateInput(input, propertyDefinition, userId, componentUniqueId);
553
554                 final Either<PropertyDefinition, StorageOperationStatus> either
555                     = toscaOperationFacade.updatePropertyOfComponent(component, propertyDefinition);
556                 if (either.isRight()) {
557                     throw new ComponentException(ActionStatus.GENERAL_ERROR);
558                 }
559             }
560         }
561     }
562
563     private void updateProperty(final PropertyDefinition propertyDefinition, final InputDefinition input, final String componentUniqueId) {
564         propertyDefinition.setParentUniqueId(componentUniqueId);
565         final GetInputValueDataDefinition getInputValueDataDefinition = new GetInputValueDataDefinition();
566         getInputValueDataDefinition.setInputId(input.getUniqueId());
567         getInputValueDataDefinition.setInputName(input.getName());
568         getInputValueDataDefinition.setPropName(propertyDefinition.getName());
569         propertyDefinition.setGetInputValues(Collections.singletonList(getInputValueDataDefinition));
570     }
571
572     private void updateInput(final InputDefinition input, final PropertyDefinition propertyDefinition,
573                              final String userId, final String componentUniqueId) {
574         input.setProperties(Collections.singletonList(new ComponentInstanceProperty(propertyDefinition)));
575         input.setInstanceUniqueId(componentUniqueId);
576         input.setOwnerId(userId);
577         input.setPropertyId(propertyDefinition.getUniqueId());
578         input.setParentPropertyType(propertyDefinition.getType());
579     }
580
581     private String extractPropertyNameFromInputName(final String inputName, final List<String> componentInstancesNames) {
582         final AtomicReference<String> result = new AtomicReference<>(inputName);
583         componentInstancesNames.forEach(cin -> result.set(result.get().replace(cin + "_", "")));
584         return result.get();
585     }
586
587     protected Either<Resource, ResponseFormat> createOrUpdateArtifacts(ArtifactsBusinessLogic.ArtifactOperationEnum operation,
588                                                                        List<ArtifactDefinition> createdArtifacts, String yamlFileName,
589                                                                        CsarInfo csarInfo, Resource preparedResource,
590                                                                        NodeTypeInfoToUpdateArtifacts nodeTypeInfoToUpdateArtifacts,
591                                                                        boolean inTransaction, boolean shouldLock) {
592         String nodeName = nodeTypeInfoToUpdateArtifacts.getNodeName();
593         Resource resource = preparedResource;
594         Map<String, EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle = nodeTypeInfoToUpdateArtifacts
595             .getNodeTypesArtifactsToHandle();
596         if (preparedResource.getResourceType() == ResourceTypeEnum.VF) {
597             if (nodeName != null && nodeTypesArtifactsToHandle.get(nodeName) != null && !nodeTypesArtifactsToHandle.get(nodeName).isEmpty()) {
598                 Either<List<ArtifactDefinition>, ResponseFormat> handleNodeTypeArtifactsRes = handleNodeTypeArtifacts(preparedResource,
599                     nodeTypesArtifactsToHandle.get(nodeName), createdArtifacts, csarInfo.getModifier(), inTransaction, true);
600                 if (handleNodeTypeArtifactsRes.isRight()) {
601                     return Either.right(handleNodeTypeArtifactsRes.right().value());
602                 }
603             }
604         } else {
605             Either<Resource, ResponseFormat> createdCsarArtifactsEither = handleVfCsarArtifacts(preparedResource, csarInfo, createdArtifacts,
606                 new ArtifactOperationInfo(false, false, operation), shouldLock, inTransaction);
607             log.trace("************* Finished to add artifacts from yaml {}", yamlFileName);
608             if (createdCsarArtifactsEither.isRight()) {
609                 return createdCsarArtifactsEither;
610             }
611             resource = createdCsarArtifactsEither.left().value();
612         }
613         return Either.left(resource);
614     }
615
616     protected Either<Resource, ResponseFormat> handleVfCsarArtifacts(Resource resource, CsarInfo csarInfo, List<ArtifactDefinition> createdArtifacts,
617                                                                      ArtifactOperationInfo artifactOperation, boolean shouldLock,
618                                                                      boolean inTransaction) {
619         if (csarInfo.getCsar() != null) {
620             createOrUpdateSingleNonMetaArtifactToComstants(resource, csarInfo, artifactOperation, shouldLock, inTransaction);
621             Either<Resource, ResponseFormat> eitherCreateResult = createOrUpdateNonMetaArtifacts(csarInfo, resource, createdArtifacts, shouldLock,
622                 inTransaction, artifactOperation);
623             if (eitherCreateResult.isRight()) {
624                 return Either.right(eitherCreateResult.right().value());
625             }
626             Either<Resource, StorageOperationStatus> eitherGerResource = toscaOperationFacade.getToscaElement(resource.getUniqueId());
627             if (eitherGerResource.isRight()) {
628                 ResponseFormat responseFormat = componentsUtils
629                     .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(eitherGerResource.right().value()), resource);
630                 return Either.right(responseFormat);
631             }
632             resource = eitherGerResource.left().value();
633             Either<ImmutablePair<String, String>, ResponseFormat> artifacsMetaCsarStatus = CsarValidationUtils
634                 .getArtifactsMeta(csarInfo.getCsar(), csarInfo.getCsarUUID(), componentsUtils);
635             if (artifacsMetaCsarStatus.isLeft()) {
636                 return getResourceResponseFormatEither(resource, csarInfo, createdArtifacts, artifactOperation, shouldLock, inTransaction,
637                     artifacsMetaCsarStatus);
638             } else {
639                 return csarArtifactsAndGroupsBusinessLogic.deleteVFModules(resource, csarInfo, shouldLock, inTransaction);
640             }
641         }
642         return Either.left(resource);
643     }
644
645     protected void createOrUpdateSingleNonMetaArtifactToComstants(Resource resource, CsarInfo csarInfo, ArtifactOperationInfo artifactOperation,
646                                                                   boolean shouldLock, boolean inTransaction) {
647         String vendorLicenseModelId = null;
648         String vfLicenseModelId = null;
649         if (artifactOperation.getArtifactOperationEnum() == ArtifactOperationEnum.UPDATE) {
650             Map<String, ArtifactDefinition> deploymentArtifactsMap = resource.getDeploymentArtifacts();
651             if (deploymentArtifactsMap != null && !deploymentArtifactsMap.isEmpty()) {
652                 for (Map.Entry<String, ArtifactDefinition> artifactEntry : deploymentArtifactsMap.entrySet()) {
653                     if (artifactEntry.getValue().getArtifactName().equalsIgnoreCase(Constants.VENDOR_LICENSE_MODEL)) {
654                         vendorLicenseModelId = artifactEntry.getValue().getUniqueId();
655                     }
656                     if (artifactEntry.getValue().getArtifactName().equalsIgnoreCase(Constants.VF_LICENSE_MODEL)) {
657                         vfLicenseModelId = artifactEntry.getValue().getUniqueId();
658                     }
659                 }
660             }
661         }
662         createOrUpdateSingleNonMetaArtifact(resource, csarInfo, CsarUtils.ARTIFACTS_PATH + Constants.VENDOR_LICENSE_MODEL,
663             Constants.VENDOR_LICENSE_MODEL, ArtifactTypeEnum.VENDOR_LICENSE.getType(), ArtifactGroupTypeEnum.DEPLOYMENT,
664             Constants.VENDOR_LICENSE_LABEL, Constants.VENDOR_LICENSE_DISPLAY_NAME, Constants.VENDOR_LICENSE_DESCRIPTION, vendorLicenseModelId,
665             artifactOperation, null, true, shouldLock, inTransaction);
666         createOrUpdateSingleNonMetaArtifact(resource, csarInfo, CsarUtils.ARTIFACTS_PATH + Constants.VF_LICENSE_MODEL, Constants.VF_LICENSE_MODEL,
667             ArtifactTypeEnum.VF_LICENSE.getType(), ArtifactGroupTypeEnum.DEPLOYMENT, Constants.VF_LICENSE_LABEL, Constants.VF_LICENSE_DISPLAY_NAME,
668             Constants.VF_LICENSE_DESCRIPTION, vfLicenseModelId, artifactOperation, null, true, shouldLock, inTransaction);
669     }
670
671     private Either<Resource, ResponseFormat> getResourceResponseFormatEither(Resource resource, CsarInfo csarInfo,
672                                                                              List<ArtifactDefinition> createdArtifacts,
673                                                                              ArtifactOperationInfo artifactOperation, boolean shouldLock,
674                                                                              boolean inTransaction,
675                                                                              Either<ImmutablePair<String, String>, ResponseFormat> artifacsMetaCsarStatus) {
676         try {
677             String artifactsFileName = artifacsMetaCsarStatus.left().value().getKey();
678             String artifactsContents = artifacsMetaCsarStatus.left().value().getValue();
679             Either<Resource, ResponseFormat> createArtifactsFromCsar;
680             if (ArtifactOperationEnum.isCreateOrLink(artifactOperation.getArtifactOperationEnum())) {
681                 createArtifactsFromCsar = csarArtifactsAndGroupsBusinessLogic
682                     .createResourceArtifactsFromCsar(csarInfo, resource, artifactsContents, artifactsFileName, createdArtifacts);
683             } else {
684                 Either<Component, ResponseFormat> result = csarArtifactsAndGroupsBusinessLogic
685                     .updateResourceArtifactsFromCsar(csarInfo, resource, artifactsContents, artifactsFileName, createdArtifacts, shouldLock,
686                         inTransaction);
687                 if ((result.left().value() instanceof Resource) && result.isLeft()) {
688                     Resource service1 = (Resource) result.left().value();
689                     createArtifactsFromCsar = Either.left(service1);
690                 } else {
691                     createArtifactsFromCsar = Either.right(result.right().value());
692                 }
693             }
694             if (createArtifactsFromCsar.isRight()) {
695                 log.debug("Couldn't create artifacts from artifacts.meta");
696                 return Either.right(createArtifactsFromCsar.right().value());
697             }
698             return Either.left(createArtifactsFromCsar.left().value());
699         } catch (Exception e) {
700             log.debug("Exception occured in getResourceResponseFormatEither, message:{}", e.getMessage(), e);
701             return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
702         }
703     }
704
705     private <T extends Component> Either<T, ResponseFormat> createOrUpdateNonMetaArtifactsComp(CsarInfo csarInfo, T component,
706                                                                                                List<ArtifactDefinition> createdArtifacts,
707                                                                                                boolean shouldLock, boolean inTransaction,
708                                                                                                ArtifactOperationInfo artifactOperation) {
709         Either<T, ResponseFormat> resStatus = null;
710         Map<String, Set<List<String>>> collectedWarningMessages = new HashMap<>();
711         try {
712             Either<List<CsarUtils.NonMetaArtifactInfo>, String> artifactPathAndNameList = getValidArtifactNames(csarInfo, collectedWarningMessages);
713             if (artifactPathAndNameList.isRight()) {
714                 return Either.right(
715                     getComponentsUtils().getResponseFormatByArtifactId(ActionStatus.ARTIFACT_NAME_INVALID, artifactPathAndNameList.right().value()));
716             }
717             EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<CsarUtils.NonMetaArtifactInfo>> vfCsarArtifactsToHandle = null;
718             if (ArtifactsBusinessLogic.ArtifactOperationEnum.isCreateOrLink(artifactOperation.getArtifactOperationEnum())) {
719                 vfCsarArtifactsToHandle = new EnumMap<>(ArtifactsBusinessLogic.ArtifactOperationEnum.class);
720                 vfCsarArtifactsToHandle.put(artifactOperation.getArtifactOperationEnum(), artifactPathAndNameList.left().value());
721             } else {
722                 Either<EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<CsarUtils.NonMetaArtifactInfo>>, ResponseFormat> findVfCsarArtifactsToHandleRes = findVfCsarArtifactsToHandle(
723                     component, artifactPathAndNameList.left().value(), csarInfo.getModifier());
724                 if (findVfCsarArtifactsToHandleRes.isRight()) {
725                     resStatus = Either.right(findVfCsarArtifactsToHandleRes.right().value());
726                 }
727                 if (resStatus == null) {
728                     vfCsarArtifactsToHandle = findVfCsarArtifactsToHandleRes.left().value();
729                 }
730             }
731             if (resStatus == null && vfCsarArtifactsToHandle != null) {
732                 resStatus = processCsarArtifacts(csarInfo, component, createdArtifacts, shouldLock, inTransaction, resStatus,
733                     vfCsarArtifactsToHandle);
734             }
735             if (resStatus == null) {
736                 resStatus = Either.left(component);
737             }
738         } catch (Exception e) {
739             resStatus = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
740             log.debug("Exception occured in createNonMetaArtifacts, message:{}", e.getMessage(), e);
741         } finally {
742             CsarUtils.handleWarningMessages(collectedWarningMessages);
743         }
744         return resStatus;
745     }
746
747     protected Either<Resource, ResponseFormat> createOrUpdateNonMetaArtifacts(CsarInfo csarInfo, Resource resource,
748                                                                               List<ArtifactDefinition> createdArtifacts, boolean shouldLock,
749                                                                               boolean inTransaction, ArtifactOperationInfo artifactOperation) {
750         return createOrUpdateNonMetaArtifactsComp(csarInfo, resource, createdArtifacts, shouldLock, inTransaction, artifactOperation);
751     }
752
753     protected <T extends Component> Either<T, ResponseFormat> processCsarArtifacts(CsarInfo csarInfo, Component comp,
754                                                                                    List<ArtifactDefinition> createdArtifacts, boolean shouldLock,
755                                                                                    boolean inTransaction, Either<T, ResponseFormat> resStatus,
756                                                                                    EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<CsarUtils.NonMetaArtifactInfo>> vfCsarArtifactsToHandle) {
757         for (Map.Entry<ArtifactsBusinessLogic.ArtifactOperationEnum, List<CsarUtils.NonMetaArtifactInfo>> currArtifactOperationPair : vfCsarArtifactsToHandle
758             .entrySet()) {
759             Optional<ResponseFormat> optionalCreateInDBError = currArtifactOperationPair.getValue().stream().map(
760                 e -> createOrUpdateSingleNonMetaArtifact(comp, csarInfo, e.getPath(), e.getArtifactName(), e.getArtifactType(),
761                     e.getArtifactGroupType(), e.getArtifactLabel(), e.getDisplayName(), CsarUtils.ARTIFACT_CREATED_FROM_CSAR, e.getArtifactUniqueId(),
762                     new ArtifactOperationInfo(false, false, currArtifactOperationPair.getKey()), createdArtifacts, e.isFromCsar(), shouldLock,
763                     inTransaction)).filter(Either::isRight).map(e -> e.right().value()).findAny();
764             if (optionalCreateInDBError.isPresent()) {
765                 resStatus = Either.right(optionalCreateInDBError.get());
766                 break;
767             }
768         }
769         return resStatus;
770     }
771
772     protected Either<Boolean, ResponseFormat> createOrUpdateSingleNonMetaArtifact(Component component, CsarInfo csarInfo, String artifactPath,
773                                                                                   String artifactFileName, String artifactType,
774                                                                                   ArtifactGroupTypeEnum artifactGroupType, String artifactLabel,
775                                                                                   String artifactDisplayName, String artifactDescription,
776                                                                                   String artifactId, ArtifactOperationInfo operation,
777                                                                                   List<ArtifactDefinition> createdArtifacts, boolean isFromCsar,
778                                                                                   boolean shouldLock, boolean inTransaction) {
779         byte[] artifactFileBytes = null;
780         if (csarInfo.getCsar().containsKey(artifactPath)) {
781             artifactFileBytes = csarInfo.getCsar().get(artifactPath);
782         }
783         Either<Boolean, ResponseFormat> result = Either.left(true);
784         if (operation.getArtifactOperationEnum() == ArtifactsBusinessLogic.ArtifactOperationEnum.UPDATE
785             || operation.getArtifactOperationEnum() == ArtifactsBusinessLogic.ArtifactOperationEnum.DELETE) {
786             if (serviceImportParseLogic.isArtifactDeletionRequired(artifactId, artifactFileBytes, isFromCsar)) {
787                 Either<ArtifactDefinition, ResponseFormat> handleDelete = artifactsBusinessLogic
788                     .handleDelete(component.getUniqueId(), artifactId, csarInfo.getModifier(), component, shouldLock, inTransaction);
789                 if (handleDelete.isRight()) {
790                     result = Either.right(handleDelete.right().value());
791                 }
792                 return result;
793             }
794             if (org.apache.commons.lang.StringUtils.isEmpty(artifactId) && artifactFileBytes != null) {
795                 operation = new ArtifactOperationInfo(false, false, ArtifactsBusinessLogic.ArtifactOperationEnum.CREATE);
796             }
797         }
798         if (artifactFileBytes != null) {
799             Map<String, Object> vendorLicenseModelJson = ArtifactUtils
800                 .buildJsonForUpdateArtifact(artifactId, artifactFileName, artifactType, artifactGroupType, artifactLabel, artifactDisplayName,
801                     artifactDescription, artifactFileBytes, null, isFromCsar);
802             Either<Either<ArtifactDefinition, Operation>, ResponseFormat> eitherNonMetaArtifacts = csarArtifactsAndGroupsBusinessLogic
803                 .createOrUpdateCsarArtifactFromJson(component, csarInfo.getModifier(), vendorLicenseModelJson, operation);
804             serviceImportParseLogic.addNonMetaCreatedArtifactsToSupportRollback(operation, createdArtifacts, eitherNonMetaArtifacts);
805             if (eitherNonMetaArtifacts.isRight()) {
806                 BeEcompErrorManager.getInstance().logInternalFlowError("UploadLicenseArtifact",
807                     "Failed to upload license artifact: " + artifactFileName + "With csar uuid: " + csarInfo.getCsarUUID(),
808                     BeEcompErrorManager.ErrorSeverity.WARNING);
809                 return Either.right(eitherNonMetaArtifacts.right().value());
810             }
811         }
812         return result;
813     }
814
815     private Either<List<ArtifactDefinition>, ResponseFormat> handleNodeTypeArtifacts(Resource nodeTypeResource,
816                                                                                      Map<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle,
817                                                                                      List<ArtifactDefinition> createdArtifacts, User user,
818                                                                                      boolean inTransaction, boolean ignoreLifecycleState) {
819         List<ArtifactDefinition> handleNodeTypeArtifactsRequestRes;
820         Either<List<ArtifactDefinition>, ResponseFormat> handleNodeTypeArtifactsRes = null;
821         Either<Resource, ResponseFormat> changeStateResponse;
822         try {
823             changeStateResponse = checkoutResource(nodeTypeResource, user, inTransaction);
824             if (changeStateResponse.isRight()) {
825                 return Either.right(changeStateResponse.right().value());
826             }
827             nodeTypeResource = changeStateResponse.left().value();
828             List<ArtifactDefinition> handledNodeTypeArtifacts = new ArrayList<>();
829             log.debug("************* Going to handle artifacts of node type resource {}. ", nodeTypeResource.getName());
830             for (Map.Entry<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>> curOperationEntry : nodeTypeArtifactsToHandle
831                 .entrySet()) {
832                 ArtifactsBusinessLogic.ArtifactOperationEnum curOperation = curOperationEntry.getKey();
833                 List<ArtifactDefinition> curArtifactsToHandle = curOperationEntry.getValue();
834                 if (curArtifactsToHandle != null && !curArtifactsToHandle.isEmpty()) {
835                     log.debug("************* Going to {} artifact to vfc {}", curOperation.name(), nodeTypeResource.getName());
836                     handleNodeTypeArtifactsRequestRes = artifactsBusinessLogic
837                         .handleArtifactsRequestForInnerVfcComponent(curArtifactsToHandle, nodeTypeResource, user, createdArtifacts,
838                             new ArtifactOperationInfo(false, ignoreLifecycleState, curOperation), false, inTransaction);
839                     if (ArtifactsBusinessLogic.ArtifactOperationEnum.isCreateOrLink(curOperation)) {
840                         createdArtifacts.addAll(handleNodeTypeArtifactsRequestRes);
841                     }
842                     handledNodeTypeArtifacts.addAll(handleNodeTypeArtifactsRequestRes);
843                 }
844             }
845             handleNodeTypeArtifactsRes = Either.left(handledNodeTypeArtifacts);
846         } catch (Exception e) {
847             ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
848             handleNodeTypeArtifactsRes = Either.right(responseFormat);
849             log.debug("Exception occured when handleVfcArtifacts, error is:{}", e.getMessage(), e);
850         }
851         return handleNodeTypeArtifactsRes;
852     }
853
854     private Either<Resource, ResponseFormat> checkoutResource(Resource resource, User user, boolean inTransaction) {
855         Either<Resource, ResponseFormat> checkoutResourceRes;
856         try {
857             if (!resource.getComponentMetadataDefinition().getMetadataDataDefinition().getState()
858                 .equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
859                 Either<? extends Component, ResponseFormat> checkoutRes = lifecycleBusinessLogic
860                     .changeComponentState(resource.getComponentType(), resource.getUniqueId(), user, LifeCycleTransitionEnum.CHECKOUT,
861                         new LifecycleChangeInfoWithAction(CERTIFICATION_ON_IMPORT,
862                             LifecycleChangeInfoWithAction.LifecycleChanceActionEnum.CREATE_FROM_CSAR), inTransaction, true);
863                 if (checkoutRes.isRight()) {
864                     checkoutResourceRes = Either.right(checkoutRes.right().value());
865                 } else {
866                     checkoutResourceRes = Either.left((Resource) checkoutRes.left().value());
867                 }
868             } else {
869                 checkoutResourceRes = Either.left(resource);
870             }
871         } catch (Exception e) {
872             ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
873             checkoutResourceRes = Either.right(responseFormat);
874             log.debug("Exception occured when checkoutResource {} , error is:{}", resource.getName(), e.getMessage(), e);
875         }
876         return checkoutResourceRes;
877     }
878
879     protected Either<Service, ResponseFormat> createOrUpdateArtifacts(ArtifactOperationEnum operation, List<ArtifactDefinition> createdArtifacts,
880                                                                       String yamlFileName, CsarInfo csarInfo, Service preparedService,
881                                                                       NodeTypeInfoToUpdateArtifacts nodeTypeInfoToUpdateArtifacts,
882                                                                       boolean inTransaction, boolean shouldLock) {
883         Either<Service, ResponseFormat> createdCsarArtifactsEither = handleVfCsarArtifacts(preparedService, csarInfo, createdArtifacts,
884             new ArtifactOperationInfo(false, false, operation), shouldLock, inTransaction);
885         log.trace("************* Finished to add artifacts from yaml {}", yamlFileName);
886         if (createdCsarArtifactsEither.isRight()) {
887             return createdCsarArtifactsEither;
888         }
889         return Either.left(createdCsarArtifactsEither.left().value());
890     }
891
892     protected Either<Service, ResponseFormat> handleVfCsarArtifacts(Service service, CsarInfo csarInfo, List<ArtifactDefinition> createdArtifacts,
893                                                                     ArtifactOperationInfo artifactOperation, boolean shouldLock,
894                                                                     boolean inTransaction) {
895         if (csarInfo.getCsar() != null) {
896             String vendorLicenseModelId = null;
897             String vfLicenseModelId = null;
898             if (artifactOperation.getArtifactOperationEnum() == ArtifactsBusinessLogic.ArtifactOperationEnum.UPDATE) {
899                 Map<String, ArtifactDefinition> deploymentArtifactsMap = service.getDeploymentArtifacts();
900                 if (deploymentArtifactsMap != null && !deploymentArtifactsMap.isEmpty()) {
901                     for (Map.Entry<String, ArtifactDefinition> artifactEntry : deploymentArtifactsMap.entrySet()) {
902                         if (artifactEntry.getValue().getArtifactName().equalsIgnoreCase(Constants.VENDOR_LICENSE_MODEL)) {
903                             vendorLicenseModelId = artifactEntry.getValue().getUniqueId();
904                         }
905                         if (artifactEntry.getValue().getArtifactName().equalsIgnoreCase(Constants.VF_LICENSE_MODEL)) {
906                             vfLicenseModelId = artifactEntry.getValue().getUniqueId();
907                         }
908                     }
909                 }
910             }
911             createOrUpdateSingleNonMetaArtifact(service, csarInfo, CsarUtils.ARTIFACTS_PATH + Constants.VENDOR_LICENSE_MODEL,
912                 Constants.VENDOR_LICENSE_MODEL, ArtifactTypeEnum.VENDOR_LICENSE.getType(), ArtifactGroupTypeEnum.DEPLOYMENT,
913                 Constants.VENDOR_LICENSE_LABEL, Constants.VENDOR_LICENSE_DISPLAY_NAME, Constants.VENDOR_LICENSE_DESCRIPTION, vendorLicenseModelId,
914                 artifactOperation, null, true, shouldLock, inTransaction);
915             createOrUpdateSingleNonMetaArtifact(service, csarInfo, CsarUtils.ARTIFACTS_PATH + Constants.VF_LICENSE_MODEL, Constants.VF_LICENSE_MODEL,
916                 ArtifactTypeEnum.VF_LICENSE.getType(), ArtifactGroupTypeEnum.DEPLOYMENT, Constants.VF_LICENSE_LABEL,
917                 Constants.VF_LICENSE_DISPLAY_NAME, Constants.VF_LICENSE_DESCRIPTION, vfLicenseModelId, artifactOperation, null, true, shouldLock,
918                 inTransaction);
919             Either<Service, ResponseFormat> eitherCreateResult = createOrUpdateNonMetaArtifacts(csarInfo, service, createdArtifacts, shouldLock,
920                 inTransaction, artifactOperation);
921             if (eitherCreateResult.isRight()) {
922                 return Either.right(eitherCreateResult.right().value());
923             }
924             Either<Service, StorageOperationStatus> eitherGerResource = toscaOperationFacade.getToscaElement(service.getUniqueId());
925             if (eitherGerResource.isRight()) {
926                 ResponseFormat responseFormat = componentsUtils
927                     .getResponseFormatByComponent(componentsUtils.convertFromStorageResponse(eitherGerResource.right().value()), service,
928                         ComponentTypeEnum.SERVICE);
929                 return Either.right(responseFormat);
930             }
931             service = eitherGerResource.left().value();
932             Either<ImmutablePair<String, String>, ResponseFormat> artifacsMetaCsarStatus = CsarValidationUtils
933                 .getArtifactsMeta(csarInfo.getCsar(), csarInfo.getCsarUUID(), componentsUtils);
934             if (artifacsMetaCsarStatus.isLeft()) {
935                 String artifactsFileName = artifacsMetaCsarStatus.left().value().getKey();
936                 String artifactsContents = artifacsMetaCsarStatus.left().value().getValue();
937                 Either<Service, ResponseFormat> createArtifactsFromCsar;
938                 if (ArtifactsBusinessLogic.ArtifactOperationEnum.isCreateOrLink(artifactOperation.getArtifactOperationEnum())) {
939                     createArtifactsFromCsar = csarArtifactsAndGroupsBusinessLogic
940                         .createResourceArtifactsFromCsar(csarInfo, service, artifactsContents, artifactsFileName, createdArtifacts);
941                 } else {
942                     Either<Component, ResponseFormat> result = csarArtifactsAndGroupsBusinessLogic
943                         .updateResourceArtifactsFromCsar(csarInfo, service, artifactsContents, artifactsFileName, createdArtifacts, shouldLock,
944                             inTransaction);
945                     if ((result.left().value() instanceof Service) && result.isLeft()) {
946                         Service service1 = (Service) result.left().value();
947                         createArtifactsFromCsar = Either.left(service1);
948                     } else {
949                         createArtifactsFromCsar = Either.right(result.right().value());
950                     }
951                 }
952                 if (createArtifactsFromCsar.isRight()) {
953                     log.debug("Couldn't create artifacts from artifacts.meta");
954                     return Either.right(createArtifactsFromCsar.right().value());
955                 }
956                 return Either.left(createArtifactsFromCsar.left().value());
957             } else {
958                 return csarArtifactsAndGroupsBusinessLogic.deleteVFModules(service, csarInfo, shouldLock, inTransaction);
959             }
960         }
961         return Either.left(service);
962     }
963
964     protected Either<Service, ResponseFormat> createOrUpdateNonMetaArtifacts(CsarInfo csarInfo, Service resource,
965                                                                              List<ArtifactDefinition> createdArtifacts, boolean shouldLock,
966                                                                              boolean inTransaction, ArtifactOperationInfo artifactOperation) {
967         return createOrUpdateNonMetaArtifactsComp(csarInfo, resource, createdArtifacts, shouldLock, inTransaction, artifactOperation);
968     }
969
970     protected Either<EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<CsarUtils.NonMetaArtifactInfo>>, ResponseFormat> findVfCsarArtifactsToHandle(
971         Component component, List<CsarUtils.NonMetaArtifactInfo> artifactPathAndNameList, User user) {
972         List<ArtifactDefinition> existingArtifacts = new ArrayList<>();
973         if (component.getDeploymentArtifacts() != null && !component.getDeploymentArtifacts().isEmpty()) {
974             existingArtifacts.addAll(component.getDeploymentArtifacts().values());
975         }
976         if (component.getArtifacts() != null && !component.getArtifacts().isEmpty()) {
977             existingArtifacts.addAll(component.getArtifacts().values());
978         }
979         existingArtifacts = existingArtifacts.stream().filter(this::isNonMetaArtifact).collect(toList());
980         List<String> artifactsToIgnore = new ArrayList<>();
981         if (component.getGroups() != null) {
982             component.getGroups().forEach(g -> {
983                 if (g.getArtifacts() != null && !g.getArtifacts().isEmpty()) {
984                     artifactsToIgnore.addAll(g.getArtifacts());
985                 }
986             });
987         }
988         existingArtifacts = existingArtifacts.stream().filter(a -> !artifactsToIgnore.contains(a.getUniqueId())).collect(toList());
989         return organizeVfCsarArtifactsByArtifactOperation(artifactPathAndNameList, existingArtifacts, component, user);
990     }
991
992     private boolean isNonMetaArtifact(ArtifactDefinition artifact) {
993         boolean result = true;
994         if (artifact.getMandatory() || artifact.getArtifactName() == null || !isValidArtifactType(artifact)) {
995             result = false;
996         }
997         return result;
998     }
999
1000     private boolean isValidArtifactType(ArtifactDefinition artifact) {
1001         final String artifactType = artifact.getArtifactType();
1002         return artifactType != null
1003             && !ArtifactTypeEnum.VENDOR_LICENSE.getType().equals(ArtifactTypeEnum.findType(artifactType))
1004             && !ArtifactTypeEnum.VF_LICENSE.getType().equals(ArtifactTypeEnum.findType(artifactType));
1005     }
1006
1007     protected Either<EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<CsarUtils.NonMetaArtifactInfo>>, ResponseFormat> organizeVfCsarArtifactsByArtifactOperation(
1008         List<CsarUtils.NonMetaArtifactInfo> artifactPathAndNameList, List<ArtifactDefinition> existingArtifactsToHandle, Component component,
1009         User user) {
1010         EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<CsarUtils.NonMetaArtifactInfo>> nodeTypeArtifactsToHandle = new EnumMap<>(
1011             ArtifactsBusinessLogic.ArtifactOperationEnum.class);
1012         Wrapper<ResponseFormat> responseWrapper = new Wrapper<>();
1013         Either<EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<CsarUtils.NonMetaArtifactInfo>>, ResponseFormat> nodeTypeArtifactsToHandleRes = Either
1014             .left(nodeTypeArtifactsToHandle);
1015         try {
1016             List<CsarUtils.NonMetaArtifactInfo> artifactsToUpload = new ArrayList<>(artifactPathAndNameList);
1017             List<CsarUtils.NonMetaArtifactInfo> artifactsToUpdate = new ArrayList<>();
1018             List<CsarUtils.NonMetaArtifactInfo> artifactsToDelete = new ArrayList<>();
1019             for (CsarUtils.NonMetaArtifactInfo currNewArtifact : artifactPathAndNameList) {
1020                 ArtifactDefinition foundArtifact;
1021                 if (!existingArtifactsToHandle.isEmpty()) {
1022                     foundArtifact = existingArtifactsToHandle.stream().filter(a -> a.getArtifactName().equals(currNewArtifact.getArtifactName()))
1023                         .findFirst().orElse(null);
1024                     if (foundArtifact != null) {
1025                         if (ArtifactTypeEnum.findType(foundArtifact.getArtifactType()).equals(currNewArtifact.getArtifactType())) {
1026                             if (!foundArtifact.getArtifactChecksum().equals(currNewArtifact.getArtifactChecksum())) {
1027                                 currNewArtifact.setArtifactUniqueId(foundArtifact.getUniqueId());
1028                                 artifactsToUpdate.add(currNewArtifact);
1029                             }
1030                             existingArtifactsToHandle.remove(foundArtifact);
1031                             artifactsToUpload.remove(currNewArtifact);
1032                         } else {
1033                             log.debug("Can't upload two artifact with the same name {}.", currNewArtifact.getArtifactName());
1034                             ResponseFormat responseFormat = ResponseFormatManager.getInstance()
1035                                 .getResponseFormat(ActionStatus.ARTIFACT_ALREADY_EXIST_IN_DIFFERENT_TYPE_IN_CSAR, currNewArtifact.getArtifactName(),
1036                                     currNewArtifact.getArtifactType(), foundArtifact.getArtifactType());
1037                             AuditingActionEnum auditingAction = artifactsBusinessLogic.detectAuditingType(
1038                                 new ArtifactOperationInfo(false, false, ArtifactsBusinessLogic.ArtifactOperationEnum.CREATE),
1039                                 foundArtifact.getArtifactChecksum());
1040                             artifactsBusinessLogic.handleAuditing(auditingAction, component, component.getUniqueId(), user, null, null,
1041                                 foundArtifact.getUniqueId(), responseFormat, component.getComponentType(), null);
1042                             responseWrapper.setInnerElement(responseFormat);
1043                             break;
1044                         }
1045                     }
1046                 }
1047             }
1048             if (responseWrapper.isEmpty()) {
1049                 for (ArtifactDefinition currArtifact : existingArtifactsToHandle) {
1050                     if (currArtifact.getIsFromCsar()) {
1051                         artifactsToDelete.add(new CsarUtils.NonMetaArtifactInfo(currArtifact.getArtifactName(), null,
1052                             ArtifactTypeEnum.findType(currArtifact.getArtifactType()), currArtifact.getArtifactGroupType(), null,
1053                             currArtifact.getUniqueId(), currArtifact.getIsFromCsar()));
1054                     } else {
1055                         artifactsToUpdate.add(new CsarUtils.NonMetaArtifactInfo(currArtifact.getArtifactName(), null,
1056                             ArtifactTypeEnum.findType(currArtifact.getArtifactType()), currArtifact.getArtifactGroupType(), null,
1057                             currArtifact.getUniqueId(), currArtifact.getIsFromCsar()));
1058                     }
1059                 }
1060             }
1061             if (responseWrapper.isEmpty()) {
1062                 if (!artifactsToUpload.isEmpty()) {
1063                     nodeTypeArtifactsToHandle.put(ArtifactsBusinessLogic.ArtifactOperationEnum.CREATE, artifactsToUpload);
1064                 }
1065                 if (!artifactsToUpdate.isEmpty()) {
1066                     nodeTypeArtifactsToHandle.put(ArtifactsBusinessLogic.ArtifactOperationEnum.UPDATE, artifactsToUpdate);
1067                 }
1068                 if (!artifactsToDelete.isEmpty()) {
1069                     nodeTypeArtifactsToHandle.put(ArtifactsBusinessLogic.ArtifactOperationEnum.DELETE, artifactsToDelete);
1070                 }
1071             }
1072             if (!responseWrapper.isEmpty()) {
1073                 nodeTypeArtifactsToHandleRes = Either.right(responseWrapper.getInnerElement());
1074             }
1075         } catch (Exception e) {
1076             ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
1077             responseWrapper.setInnerElement(responseFormat);
1078             log.debug("Exception occured when findNodeTypeArtifactsToHandle, error is:{}", e.getMessage(), e);
1079             nodeTypeArtifactsToHandleRes = Either.right(responseWrapper.getInnerElement());
1080         }
1081         return nodeTypeArtifactsToHandleRes;
1082     }
1083
1084     protected Either<List<CsarUtils.NonMetaArtifactInfo>, String> getValidArtifactNames(CsarInfo csarInfo,
1085                                                                                         Map<String, Set<List<String>>> collectedWarningMessages) {
1086         List<CsarUtils.NonMetaArtifactInfo> artifactPathAndNameList = csarInfo.getCsar().entrySet().stream()
1087             .filter(e -> Pattern.compile(VF_NODE_TYPE_ARTIFACTS_PATH_PATTERN).matcher(e.getKey()).matches())
1088             .map(e -> CsarUtils.validateNonMetaArtifact(e.getKey(), e.getValue(), collectedWarningMessages)).filter(Either::isLeft)
1089             .map(e -> e.left().value()).collect(toList());
1090         Pattern englishNumbersAndUnderScoresOnly = Pattern.compile(CsarUtils.VALID_ENGLISH_ARTIFACT_NAME);
1091         for (CsarUtils.NonMetaArtifactInfo nonMetaArtifactInfo : artifactPathAndNameList) {
1092             if (!englishNumbersAndUnderScoresOnly.matcher(nonMetaArtifactInfo.getDisplayName()).matches()) {
1093                 return Either.right(nonMetaArtifactInfo.getArtifactName());
1094             }
1095         }
1096         return Either.left(artifactPathAndNameList);
1097     }
1098
1099     protected Either<Service, ResponseFormat> createGroupsOnResource(Service service, Map<String, GroupDefinition> groups) {
1100         if (groups != null && !groups.isEmpty()) {
1101             List<GroupDefinition> groupsAsList = updateGroupsMembersUsingResource(groups, service);
1102             serviceImportParseLogic.handleGroupsProperties(service, groups);
1103             serviceImportParseLogic.fillGroupsFinalFields(groupsAsList);
1104             Either<List<GroupDefinition>, ResponseFormat> createGroups = groupBusinessLogic.createGroups(service, groupsAsList, true);
1105             if (createGroups.isRight()) {
1106                 return Either.right(createGroups.right().value());
1107             }
1108         } else {
1109             return Either.left(service);
1110         }
1111         return getServiceResponseFormatEither(service);
1112     }
1113
1114     private Either<Service, ResponseFormat> createPoliciesOnResource(final Service service,
1115                                                                      final Map<String, PolicyDefinition> policies) {
1116         if (MapUtils.isEmpty(policies)) {
1117             return Either.left(service);
1118         }
1119         final Map<String, List<AttributeDefinition>> instanceAttributeMap =
1120             service.getComponentInstancesAttributes()
1121                 .entrySet().stream()
1122                 .collect(
1123                     toMap(Entry::getKey,
1124                         entry -> entry.getValue().stream().map(AttributeDefinition.class::cast).collect(toList()))
1125                 );
1126         policies.values().stream()
1127             .map(PolicyDataDefinition::getProperties)
1128             .flatMap(Collection::stream)
1129             .filter(PropertyDataDefinition::isToscaFunction)
1130             .forEach(policyDefinition ->
1131                 toscaFunctionService
1132                     .updateFunctionWithDataFromSelfComponent(policyDefinition.getToscaFunction(), service, service.getComponentInstancesProperties(),
1133                         instanceAttributeMap)
1134             );
1135         policyBusinessLogic.createPolicies(service, policies);
1136         return getServiceResponseFormatEither(service);
1137     }
1138
1139     private Either<Service, ResponseFormat> getServiceResponseFormatEither(Service service) {
1140         Either<Service, StorageOperationStatus> updatedResource = toscaOperationFacade.getToscaElement(service.getUniqueId());
1141         if (updatedResource.isRight()) {
1142             ResponseFormat responseFormat = componentsUtils
1143                 .getResponseFormatByComponent(componentsUtils.convertFromStorageResponse(updatedResource.right().value()), service,
1144                     ComponentTypeEnum.SERVICE);
1145             return Either.right(responseFormat);
1146         }
1147         return Either.left(updatedResource.left().value());
1148     }
1149
1150     protected List<GroupDefinition> updateGroupsMembersUsingResource(Map<String, GroupDefinition> groups, Service component) {
1151         List<GroupDefinition> result = new ArrayList<>();
1152         List<ComponentInstance> componentInstances = component.getComponentInstances();
1153         if (groups != null) {
1154             for (Map.Entry<String, GroupDefinition> entry : groups.entrySet()) {
1155                 String groupName = entry.getKey();
1156                 GroupDefinition groupDefinition = entry.getValue();
1157                 GroupDefinition updatedGroupDefinition = new GroupDefinition(groupDefinition);
1158                 updatedGroupDefinition.setMembers(null);
1159                 Map<String, String> members = groupDefinition.getMembers();
1160                 if (members != null) {
1161                     serviceImportParseLogic.updateGroupMembers(groups, updatedGroupDefinition, component, componentInstances, groupName, members);
1162                 }
1163                 result.add(updatedGroupDefinition);
1164             }
1165         }
1166         return result;
1167     }
1168
1169     protected Resource createRIAndRelationsFromYaml(String yamlName, Resource resource,
1170                                                     Map<String, UploadComponentInstanceInfo> uploadComponentInstanceInfoMap,
1171                                                     String topologyTemplateYaml, List<ArtifactDefinition> nodeTypesNewCreatedArtifacts,
1172                                                     Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo,
1173                                                     Map<String, EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToCreate,
1174                                                     String nodeName) {
1175         try {
1176             log.debug("************* Going to create all nodes {}", yamlName);
1177             handleNodeTypes(yamlName, resource, topologyTemplateYaml, false, nodeTypesArtifactsToCreate, nodeTypesNewCreatedArtifacts, nodeTypesInfo,
1178                 csarInfo, nodeName);
1179             log.debug("************* Going to create all resource instances {}", yamlName);
1180             resource = createResourceInstances(yamlName, resource, uploadComponentInstanceInfoMap, csarInfo.getCreatedNodes());
1181             log.debug("************* Finished to create all resource instances {}", yamlName);
1182             resource = createResourceInstancesRelations(csarInfo.getModifier(), yamlName, resource, uploadComponentInstanceInfoMap);
1183             log.debug("************* Going to create positions {}", yamlName);
1184             compositionBusinessLogic.setPositionsForComponentInstances(resource, csarInfo.getModifier().getUserId());
1185             log.debug("************* Finished to set positions {}", yamlName);
1186             return resource;
1187         } catch (Exception e) {
1188             throw new ComponentException(ActionStatus.GENERAL_ERROR);
1189         }
1190     }
1191
1192     protected Resource createResourceInstancesRelations(User user, String yamlName, Resource resource,
1193                                                         Map<String, UploadComponentInstanceInfo> uploadResInstancesMap) {
1194         log.debug("#createResourceInstancesRelations - Going to create relations ");
1195         List<ComponentInstance> componentInstancesList = resource.getComponentInstances();
1196         if (((MapUtils.isEmpty(uploadResInstancesMap) || CollectionUtils.isEmpty(componentInstancesList)) &&
1197             resource.getResourceType() != ResourceTypeEnum.PNF)) { // PNF can have no resource instances
1198             log.debug("#createResourceInstancesRelations - No instances found in the resource {} is empty, yaml template file name {}, ",
1199                 resource.getUniqueId(), yamlName);
1200             BeEcompErrorManager.getInstance()
1201                 .logInternalDataError("createResourceInstancesRelations", "No instances found in a resource or nn yaml template. ",
1202                     BeEcompErrorManager.ErrorSeverity.ERROR);
1203             throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName));
1204         }
1205         Map<String, List<ComponentInstanceProperty>> instProperties = new HashMap<>();
1206         Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilities = new HashMap<>();
1207         Map<ComponentInstance, Map<String, List<RequirementDefinition>>> instRequirements = new HashMap<>();
1208         Map<String, Map<String, ArtifactDefinition>> instDeploymentArtifacts = new HashMap<>();
1209         Map<String, Map<String, ArtifactDefinition>> instArtifacts = new HashMap<>();
1210         Map<String, List<AttributeDefinition>> instAttributes = new HashMap<>();
1211         Map<String, Resource> originCompMap = new HashMap<>();
1212         List<RequirementCapabilityRelDef> relations = new ArrayList<>();
1213         Map<String, List<ComponentInstanceInput>> instInputs = new HashMap<>();
1214         Map<String, UploadNodeFilterInfo> instNodeFilter = new HashMap<>();
1215         Map<String, Map<String, InterfaceDefinition>> instInterfaces = new HashMap<>();
1216         log.debug("enter ServiceImportBusinessLogic createResourceInstancesRelations#createResourceInstancesRelations - Before get all datatypes. ");
1217         final ApplicationDataTypeCache applicationDataTypeCache = serviceBusinessLogic.applicationDataTypeCache;
1218         if (applicationDataTypeCache != null) {
1219             Resource finalResource = resource;
1220             uploadResInstancesMap.values().forEach(
1221                 i -> processComponentInstance(yamlName, finalResource, componentInstancesList,
1222                     componentsUtils.getAllDataTypes(applicationDataTypeCache, finalResource.getModel()), instProperties, instCapabilities,
1223                     instRequirements, instDeploymentArtifacts, instArtifacts, instAttributes, originCompMap, instInputs, instNodeFilter,
1224                     instInterfaces, i));
1225         }
1226         serviceImportParseLogic.associateComponentInstancePropertiesToComponent(yamlName, resource, instProperties);
1227         serviceImportParseLogic.associateComponentInstanceInputsToComponent(yamlName, resource, instInputs);
1228         serviceImportParseLogic.associateDeploymentArtifactsToInstances(user, yamlName, resource, instDeploymentArtifacts);
1229         serviceImportParseLogic.associateArtifactsToInstances(yamlName, resource, instArtifacts);
1230         serviceImportParseLogic.associateOrAddCalculatedCapReq(yamlName, resource, instCapabilities, instRequirements);
1231         serviceImportParseLogic.associateInstAttributeToComponentToInstances(yamlName, resource, instAttributes);
1232         resource = serviceImportParseLogic.getResourceAfterCreateRelations(resource);
1233         serviceImportParseLogic.addRelationsToRI(yamlName, resource, uploadResInstancesMap, componentInstancesList, relations);
1234         serviceImportParseLogic.associateResourceInstances(yamlName, resource, relations);
1235         handleSubstitutionMappings(resource, uploadResInstancesMap);
1236         log.debug("************* in create relations, getResource start");
1237         Either<Resource, StorageOperationStatus> eitherGetResource = toscaOperationFacade.getToscaElement(resource.getUniqueId());
1238         log.debug("************* in create relations, getResource end");
1239         if (eitherGetResource.isRight()) {
1240             throw new ComponentException(
1241                 componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(eitherGetResource.right().value()), resource));
1242         }
1243         return eitherGetResource.left().value();
1244     }
1245
1246     protected void processProperty(Resource resource, Map<String, DataTypeDefinition> allDataTypes,
1247                                    Map<String, InputDefinition> currPropertiesMap, List<ComponentInstanceInput> instPropList,
1248                                    List<UploadPropInfo> propertyList) {
1249         UploadPropInfo propertyInfo = propertyList.get(0);
1250         String propName = propertyInfo.getName();
1251         if (!currPropertiesMap.containsKey(propName)) {
1252             throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND, propName));
1253         }
1254         processProperty(allDataTypes, currPropertiesMap, instPropList, propertyInfo, propName, resource.getInputs());
1255     }
1256
1257     private void processProperty(Map<String, DataTypeDefinition> allDataTypes, Map<String, InputDefinition> currPropertiesMap,
1258                                  List<ComponentInstanceInput> instPropList, UploadPropInfo propertyInfo, String propName,
1259                                  List<InputDefinition> inputs2) {
1260         InputDefinition curPropertyDef = currPropertiesMap.get(propName);
1261         ComponentInstanceInput property = null;
1262         String value = null;
1263         List<GetInputValueDataDefinition> getInputs = null;
1264         boolean isValidate = true;
1265         if (propertyInfo.getValue() != null) {
1266             getInputs = propertyInfo.getGet_input();
1267             isValidate = getInputs == null || getInputs.isEmpty();
1268             if (isValidate) {
1269                 value = getPropertyJsonStringValue(propertyInfo.getValue(), curPropertyDef.getType());
1270             } else {
1271                 value = getPropertyJsonStringValue(propertyInfo.getValue(), TypeUtils.ToscaTagNamesEnum.GET_INPUT.getElementName());
1272             }
1273         }
1274         property = new ComponentInstanceInput(curPropertyDef, value, null);
1275         String validPropertyVAlue = serviceBusinessLogic.validatePropValueBeforeCreate(property, value, isValidate, allDataTypes);
1276         property.setValue(validPropertyVAlue);
1277         if (isNotEmpty(getInputs)) {
1278             List<GetInputValueDataDefinition> getInputValues = new ArrayList<>();
1279             for (GetInputValueDataDefinition getInput : getInputs) {
1280                 List<InputDefinition> inputs = inputs2;
1281                 if (CollectionUtils.isEmpty(inputs)) {
1282                     throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
1283                 }
1284                 Optional<InputDefinition> optional = inputs.stream().filter(p -> p.getName().equals(getInput.getInputName())).findAny();
1285                 if (!optional.isPresent()) {
1286                     throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
1287                 }
1288                 InputDefinition input = optional.get();
1289                 getInput.setInputId(input.getUniqueId());
1290                 getInputValues.add(getInput);
1291                 GetInputValueDataDefinition getInputIndex = getInput.getGetInputIndex();
1292                 processGetInput(getInputValues, inputs, getInputIndex);
1293             }
1294             property.setGetInputValues(getInputValues);
1295         }
1296         instPropList.add(property);
1297         currPropertiesMap.remove(property.getName());
1298     }
1299
1300     protected void handleSubstitutionMappings(Resource resource, Map<String, UploadComponentInstanceInfo> uploadResInstancesMap) {
1301         if (resource.getResourceType() == ResourceTypeEnum.VF) {
1302             Either<Resource, StorageOperationStatus> getResourceRes = toscaOperationFacade.getToscaFullElement(resource.getUniqueId());
1303             if (getResourceRes.isRight()) {
1304                 ResponseFormat responseFormat = componentsUtils
1305                     .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(getResourceRes.right().value()), resource);
1306                 throw new ComponentException(responseFormat);
1307             }
1308             getResourceRes = updateCalculatedCapReqWithSubstitutionMappings(getResourceRes.left().value(), uploadResInstancesMap);
1309             if (getResourceRes.isRight()) {
1310                 ResponseFormat responseFormat = componentsUtils
1311                     .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(getResourceRes.right().value()), resource);
1312                 throw new ComponentException(responseFormat);
1313             }
1314         }
1315     }
1316
1317     protected Resource createResourceInstances(String yamlName, Resource resource, Map<String, UploadComponentInstanceInfo> uploadResInstancesMap,
1318                                                Map<String, Resource> nodeNamespaceMap) {
1319         Either<Resource, ResponseFormat> eitherResource = null;
1320         log.debug("createResourceInstances is {} - going to create resource instanse from CSAR", yamlName);
1321         if (MapUtils.isEmpty(uploadResInstancesMap) && resource.getResourceType() != ResourceTypeEnum.PNF) { // PNF can have no resource instances
1322             ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE);
1323             throw new ComponentException(responseFormat);
1324         }
1325         Map<String, Resource> existingNodeTypeMap = new HashMap<>();
1326         if (MapUtils.isNotEmpty(nodeNamespaceMap)) {
1327             nodeNamespaceMap.forEach((k, v) -> existingNodeTypeMap.put(v.getToscaResourceName(), v));
1328         }
1329         Map<ComponentInstance, Resource> resourcesInstancesMap = new HashMap<>();
1330         uploadResInstancesMap.values()
1331             .forEach(i -> createAndAddResourceInstance(i, yamlName, resource, nodeNamespaceMap, existingNodeTypeMap, resourcesInstancesMap));
1332         if (MapUtils.isNotEmpty(resourcesInstancesMap)) {
1333             try {
1334                 toscaOperationFacade.associateComponentInstancesToComponent(resource, resourcesInstancesMap, false, false);
1335             } catch (StorageException exp) {
1336                 if (exp.getStorageOperationStatus() != null && exp.getStorageOperationStatus() != StorageOperationStatus.OK) {
1337                     log.debug("Failed to add component instances to container component {}", resource.getName());
1338                     ResponseFormat responseFormat = componentsUtils
1339                         .getResponseFormat(componentsUtils.convertFromStorageResponse(exp.getStorageOperationStatus()));
1340                     eitherResource = Either.right(responseFormat);
1341                     throw new ByResponseFormatComponentException(eitherResource.right().value());
1342                 }
1343             }
1344         }
1345         log.debug("*************Going to get resource {}", resource.getUniqueId());
1346         Either<Resource, StorageOperationStatus> eitherGetResource = toscaOperationFacade
1347             .getToscaElement(resource.getUniqueId(), serviceImportParseLogic.getComponentWithInstancesFilter());
1348         log.debug("*************finished to get resource {}", resource.getUniqueId());
1349         if (eitherGetResource.isRight()) {
1350             ResponseFormat responseFormat = componentsUtils
1351                 .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(eitherGetResource.right().value()), resource);
1352             throw new ComponentException(responseFormat);
1353         }
1354         if (CollectionUtils.isEmpty(eitherGetResource.left().value().getComponentInstances()) &&
1355             resource.getResourceType() != ResourceTypeEnum.PNF) { // PNF can have no resource instances
1356             log.debug("Error when create resource instance from csar. ComponentInstances list empty");
1357             BeEcompErrorManager.getInstance().logBeDaoSystemError("Error when create resource instance from csar. ComponentInstances list empty");
1358             throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE));
1359         }
1360         return eitherGetResource.left().value();
1361     }
1362
1363     protected void handleNodeTypes(String yamlName, Resource resource, String topologyTemplateYaml, boolean needLock,
1364                                    Map<String, EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle,
1365                                    List<ArtifactDefinition> nodeTypesNewCreatedArtifacts, Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo,
1366                                    String nodeName) {
1367         try {
1368             for (Map.Entry<String, NodeTypeInfo> nodeTypeEntry : nodeTypesInfo.entrySet()) {
1369                 if (nodeTypeEntry.getValue().isNested()) {
1370                     handleNestedVfc(resource, nodeTypesArtifactsToHandle, nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo,
1371                         nodeTypeEntry.getKey());
1372                     log.trace("************* finished to create node {}", nodeTypeEntry.getKey());
1373                 }
1374             }
1375             Map<String, Object> mappedToscaTemplate = null;
1376             if (org.apache.commons.lang.StringUtils.isNotEmpty(nodeName) && MapUtils.isNotEmpty(nodeTypesInfo) && nodeTypesInfo
1377                 .containsKey(nodeName)) {
1378                 mappedToscaTemplate = nodeTypesInfo.get(nodeName).getMappedToscaTemplate();
1379             }
1380             if (MapUtils.isEmpty(mappedToscaTemplate)) {
1381                 mappedToscaTemplate = (Map<String, Object>) new Yaml().load(topologyTemplateYaml);
1382             }
1383             createResourcesFromYamlNodeTypesList(yamlName, resource, mappedToscaTemplate, needLock, nodeTypesArtifactsToHandle,
1384                 nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo);
1385         } catch (ComponentException e) {
1386             ResponseFormat responseFormat =
1387                 e.getResponseFormat() != null ? e.getResponseFormat() : componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams());
1388             componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, AuditingActionEnum.IMPORT_RESOURCE);
1389             throw e;
1390         } catch (StorageException e) {
1391             ResponseFormat responseFormat = componentsUtils
1392                 .getResponseFormat(componentsUtils.convertFromStorageResponse(e.getStorageOperationStatus()));
1393             componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, AuditingActionEnum.IMPORT_RESOURCE);
1394             throw e;
1395         } catch (Exception e) {
1396             log.debug("Exception occured when handleNodeTypes, error is:{}", e.getMessage(), e);
1397             throw new ComponentException(ActionStatus.GENERAL_ERROR);
1398         }
1399     }
1400
1401     protected Resource handleNestedVfc(Service service,
1402                                        Map<String, EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>>> nodesArtifactsToHandle,
1403                                        List<ArtifactDefinition> createdArtifacts, Map<String, NodeTypeInfo> nodesInfo, CsarInfo csarInfo,
1404                                        String nodeName) {
1405         try {
1406             String yamlName = nodesInfo.get(nodeName).getTemplateFileName();
1407             Map<String, Object> nestedVfcJsonMap = nodesInfo.get(nodeName).getMappedToscaTemplate();
1408             createResourcesFromYamlNodeTypesList(yamlName, service, nestedVfcJsonMap, false, nodesArtifactsToHandle, createdArtifacts, nodesInfo,
1409                 csarInfo);
1410             log.debug("************* Finished to create node types from yaml {}", yamlName);
1411             if (nestedVfcJsonMap.containsKey(TypeUtils.ToscaTagNamesEnum.TOPOLOGY_TEMPLATE.getElementName())) {
1412                 log.debug("************* Going to handle complex VFC from yaml {}", yamlName);
1413                 return handleComplexVfc(nodesArtifactsToHandle, createdArtifacts, nodesInfo, csarInfo, nodeName, yamlName);
1414             }
1415             return new Resource();
1416         } catch (Exception e) {
1417             log.debug("Exception occured when handleNestedVFc, error is:{}", e.getMessage(), e);
1418             throw new ComponentException(ActionStatus.GENERAL_ERROR);
1419         }
1420     }
1421
1422     protected Resource handleNestedVfc(Resource resource,
1423                                        Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodesArtifactsToHandle,
1424                                        List<ArtifactDefinition> createdArtifacts, Map<String, NodeTypeInfo> nodesInfo, CsarInfo csarInfo,
1425                                        String nodeName) {
1426         String yamlName = nodesInfo.get(nodeName).getTemplateFileName();
1427         Map<String, Object> nestedVfcJsonMap = nodesInfo.get(nodeName).getMappedToscaTemplate();
1428         log.debug("************* Going to create node types from yaml {}", yamlName);
1429         createResourcesFromYamlNodeTypesList(yamlName, resource, nestedVfcJsonMap, false, nodesArtifactsToHandle, createdArtifacts, nodesInfo,
1430             csarInfo);
1431         if (nestedVfcJsonMap.containsKey(TypeUtils.ToscaTagNamesEnum.TOPOLOGY_TEMPLATE.getElementName())) {
1432             log.debug("************* Going to handle complex VFC from yaml {}", yamlName);
1433             resource = handleComplexVfc(resource, nodesArtifactsToHandle, createdArtifacts, nodesInfo, csarInfo, nodeName, yamlName);
1434         }
1435         return resource;
1436     }
1437
1438     protected Resource handleComplexVfc(Resource resource,
1439                                         Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodesArtifactsToHandle,
1440                                         List<ArtifactDefinition> createdArtifacts, Map<String, NodeTypeInfo> nodesInfo, CsarInfo csarInfo,
1441                                         String nodeName, String yamlName) {
1442         Resource oldComplexVfc = null;
1443         Resource newComplexVfc = serviceImportParseLogic.buildValidComplexVfc(resource, csarInfo, nodeName, nodesInfo);
1444         Either<Resource, StorageOperationStatus> oldComplexVfcRes = toscaOperationFacade
1445             .getFullLatestComponentByToscaResourceName(newComplexVfc.getToscaResourceName());
1446         if (oldComplexVfcRes.isRight() && oldComplexVfcRes.right().value() == StorageOperationStatus.NOT_FOUND) {
1447             oldComplexVfcRes = toscaOperationFacade.getFullLatestComponentByToscaResourceName(
1448                 serviceImportParseLogic.buildNestedToscaResourceName(ResourceTypeEnum.VF.name(), csarInfo.getVfResourceName(), nodeName).getRight());
1449         }
1450         if (oldComplexVfcRes.isRight() && oldComplexVfcRes.right().value() != StorageOperationStatus.NOT_FOUND) {
1451             throw new ComponentException(ActionStatus.GENERAL_ERROR);
1452         } else if (oldComplexVfcRes.isLeft()) {
1453             log.debug(VALIDATE_DERIVED_BEFORE_UPDATE);
1454             Either<Boolean, ResponseFormat> eitherValidation = serviceImportParseLogic
1455                 .validateNestedDerivedFromDuringUpdate(oldComplexVfcRes.left().value(), newComplexVfc,
1456                     ValidationUtils.hasBeenCertified(oldComplexVfcRes.left().value().getVersion()));
1457             if (eitherValidation.isLeft()) {
1458                 oldComplexVfc = oldComplexVfcRes.left().value();
1459             }
1460         }
1461         newComplexVfc = handleComplexVfc(nodesArtifactsToHandle, createdArtifacts, nodesInfo, csarInfo, nodeName, yamlName, oldComplexVfc,
1462             newComplexVfc);
1463         csarInfo.getCreatedNodesToscaResourceNames().put(nodeName, newComplexVfc.getToscaResourceName());
1464         LifecycleChangeInfoWithAction lifecycleChangeInfo = new LifecycleChangeInfoWithAction(CERTIFICATION_ON_IMPORT,
1465             LifecycleChangeInfoWithAction.LifecycleChanceActionEnum.CREATE_FROM_CSAR);
1466         log.debug("Going to certify cvfc {}. ", newComplexVfc.getName());
1467         final Resource result = serviceImportParseLogic
1468             .propagateStateToCertified(csarInfo.getModifier(), newComplexVfc, lifecycleChangeInfo, true, false, true);
1469         csarInfo.getCreatedNodes().put(nodeName, result);
1470         csarInfo.removeNodeFromQueue();
1471         return result;
1472     }
1473
1474     private Map<String, Resource> createResourcesFromYamlNodeTypesList(String yamlName, Resource resource, Map<String, Object> mappedToscaTemplate,
1475                                                                        boolean needLock,
1476                                                                        Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle,
1477                                                                        List<ArtifactDefinition> nodeTypesNewCreatedArtifacts,
1478                                                                        Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo) {
1479         Either<String, ImportUtils.ResultStatusEnum> toscaVersion = findFirstToscaStringElement(mappedToscaTemplate,
1480             TypeUtils.ToscaTagNamesEnum.TOSCA_VERSION);
1481         if (toscaVersion.isRight()) {
1482             throw new ComponentException(ActionStatus.INVALID_TOSCA_TEMPLATE);
1483         }
1484         Map<String, Object> mapToConvert = new HashMap<>();
1485         mapToConvert.put(TypeUtils.ToscaTagNamesEnum.TOSCA_VERSION.getElementName(), toscaVersion.left().value());
1486         Map<String, Object> nodeTypes = serviceImportParseLogic.getNodeTypesFromTemplate(mappedToscaTemplate);
1487         createNodeTypes(yamlName, resource, needLock, nodeTypesArtifactsToHandle, nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo, mapToConvert,
1488             nodeTypes);
1489         return csarInfo.getCreatedNodes();
1490     }
1491
1492     protected void createNodeTypes(String yamlName, Resource resource, boolean needLock,
1493                                    Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle,
1494                                    List<ArtifactDefinition> nodeTypesNewCreatedArtifacts, Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo,
1495                                    Map<String, Object> mapToConvert, Map<String, Object> nodeTypes) {
1496         Iterator<Map.Entry<String, Object>> nodesNameValueIter = nodeTypes.entrySet().iterator();
1497         Resource vfcCreated = null;
1498         while (nodesNameValueIter.hasNext()) {
1499             Map.Entry<String, Object> nodeType = nodesNameValueIter.next();
1500             Map<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle =
1501                 nodeTypesArtifactsToHandle == null || nodeTypesArtifactsToHandle.isEmpty() ? null : nodeTypesArtifactsToHandle.get(nodeType.getKey());
1502             if (nodeTypesInfo.containsKey(nodeType.getKey())) {
1503                 log.trace("************* Going to handle nested vfc {}", nodeType.getKey());
1504                 vfcCreated = handleNestedVfc(resource, nodeTypesArtifactsToHandle, nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo,
1505                     nodeType.getKey());
1506                 log.trace("************* Finished to handle nested vfc {}", nodeType.getKey());
1507             } else if (csarInfo.getCreatedNodesToscaResourceNames() != null && !csarInfo.getCreatedNodesToscaResourceNames()
1508                 .containsKey(nodeType.getKey())) {
1509                 log.trace("************* Going to create node {}", nodeType.getKey());
1510                 ImmutablePair<Resource, ActionStatus> resourceCreated = createNodeTypeResourceFromYaml(yamlName, nodeType, csarInfo.getModifier(),
1511                     mapToConvert, resource, needLock, nodeTypeArtifactsToHandle, nodeTypesNewCreatedArtifacts, true, csarInfo, true);
1512                 log.debug("************* Finished to create node {}", nodeType.getKey());
1513                 vfcCreated = resourceCreated.getLeft();
1514                 csarInfo.getCreatedNodesToscaResourceNames().put(nodeType.getKey(), vfcCreated.getToscaResourceName());
1515             }
1516             if (vfcCreated != null) {
1517                 csarInfo.getCreatedNodes().put(nodeType.getKey(), vfcCreated);
1518             }
1519             mapToConvert.remove(TypeUtils.ToscaTagNamesEnum.NODE_TYPES.getElementName());
1520         }
1521     }
1522
1523     protected ImmutablePair<Resource, ActionStatus> createNodeTypeResourceFromYaml(String yamlName, Map.Entry<String, Object> nodeNameValue,
1524                                                                                    User user, Map<String, Object> mapToConvert, Resource resourceVf,
1525                                                                                    boolean needLock,
1526                                                                                    Map<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle,
1527                                                                                    List<ArtifactDefinition> nodeTypesNewCreatedArtifacts,
1528                                                                                    boolean forceCertificationAllowed, CsarInfo csarInfo,
1529                                                                                    boolean isNested) {
1530         final var validatedUser = serviceBusinessLogic.validateUser(user, "CheckIn Resource", resourceVf, AuditingActionEnum.CHECKIN_RESOURCE,
1531             true);
1532         UploadResourceInfo resourceMetaData = serviceImportParseLogic.fillResourceMetadata(yamlName, resourceVf, nodeNameValue.getKey(),
1533             validatedUser);
1534         String singleVfcYaml = serviceImportParseLogic.buildNodeTypeYaml(nodeNameValue, mapToConvert, resourceMetaData.getResourceType(), csarInfo);
1535         return serviceImportParseLogic.createResourceFromNodeType(singleVfcYaml, resourceMetaData, validatedUser, true, needLock,
1536             nodeTypeArtifactsToHandle,
1537             nodeTypesNewCreatedArtifacts, forceCertificationAllowed, csarInfo, nodeNameValue.getKey(), isNested);
1538     }
1539
1540     protected Service createRIAndRelationsFromYaml(String yamlName, Service service,
1541                                                    Map<String, UploadComponentInstanceInfo> uploadComponentInstanceInfoMap,
1542                                                    String topologyTemplateYaml, List<ArtifactDefinition> nodeTypesNewCreatedArtifacts,
1543                                                    Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo,
1544                                                    Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToCreate,
1545                                                    String nodeName) {
1546         log.debug("************* Going to create all nodes {}", yamlName);
1547         handleServiceNodeTypes(yamlName, service, topologyTemplateYaml, false, nodeTypesArtifactsToCreate, nodeTypesNewCreatedArtifacts,
1548             nodeTypesInfo, csarInfo, nodeName);
1549         if (MapUtils.isNotEmpty(uploadComponentInstanceInfoMap)) {
1550             log.debug("************* Going to create all resource instances {}", yamlName);
1551             service = createServiceInstances(yamlName, service, uploadComponentInstanceInfoMap, csarInfo.getCreatedNodes());
1552             log.debug("************* Going to create all relations {}", yamlName);
1553             service = createServiceInstancesRelations(csarInfo.getModifier(), yamlName, service, uploadComponentInstanceInfoMap);
1554             log.debug("************* Going to create positions {}", yamlName);
1555             compositionBusinessLogic.setPositionsForComponentInstances(service, csarInfo.getModifier().getUserId());
1556             log.debug("************* Finished to set positions {}", yamlName);
1557         }
1558         return service;
1559     }
1560
1561     protected Service createServiceInstancesRelations(User user, String yamlName, Service service,
1562                                                       Map<String, UploadComponentInstanceInfo> uploadResInstancesMap) {
1563         log.debug("#createResourceInstancesRelations - Going to create relations ");
1564         List<ComponentInstance> componentInstancesList = service.getComponentInstances();
1565         if (MapUtils.isEmpty(uploadResInstancesMap) || CollectionUtils.isEmpty(componentInstancesList)) { // PNF can have no resource instances
1566             log.debug("#createResourceInstancesRelations - No instances found in the resource {} is empty, yaml template file name {}, ",
1567                 service.getUniqueId(), yamlName);
1568             BeEcompErrorManager.getInstance()
1569                 .logInternalDataError("createResourceInstancesRelations", "No instances found in a component or nn yaml template. ",
1570                     BeEcompErrorManager.ErrorSeverity.ERROR);
1571             throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName));
1572         }
1573         Map<String, List<ComponentInstanceProperty>> instProperties = new HashMap<>();
1574         Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilities = new HashMap<>();
1575         Map<ComponentInstance, Map<String, List<RequirementDefinition>>> instRequirements = new HashMap<>();
1576         Map<String, Map<String, ArtifactDefinition>> instDeploymentArtifacts = new HashMap<>();
1577         Map<String, Map<String, ArtifactDefinition>> instArtifacts = new HashMap<>();
1578         Map<String, List<AttributeDefinition>> instAttributes = new HashMap<>();
1579         Map<String, Resource> originCompMap = new HashMap<>();
1580         List<RequirementCapabilityRelDef> relations = new ArrayList<>();
1581         Map<String, List<ComponentInstanceInput>> instInputs = new HashMap<>();
1582         Map<String, UploadNodeFilterInfo> instNodeFilter = new HashMap<>();
1583         Map<String, Map<String, InterfaceDefinition>> instInterfaces = new HashMap<>();
1584         log.debug("enter ServiceImportBusinessLogic  createServiceInstancesRelations#createResourceInstancesRelations - Before get all datatypes. ");
1585         final ApplicationDataTypeCache applicationDataTypeCache = serviceBusinessLogic.applicationDataTypeCache;
1586         if (applicationDataTypeCache != null) {
1587             final Map<String, DataTypeDefinition> allDataTypesMap =
1588                 componentsUtils.getAllDataTypes(applicationDataTypeCache, service.getModel());
1589             final Service service1 = service;
1590             uploadResInstancesMap.values().forEach(
1591                 i -> processComponentInstance(yamlName, service1, componentInstancesList,
1592                     allDataTypesMap, instProperties,
1593                     instCapabilities, instRequirements, instDeploymentArtifacts, instArtifacts, instAttributes, originCompMap, instInputs,
1594                     instNodeFilter, instInterfaces, i)
1595             );
1596         }
1597         updatePropertyToscaFunctionData(service, instProperties, instAttributes);
1598         serviceImportParseLogic.associateComponentInstancePropertiesToComponent(yamlName, service, instProperties);
1599         serviceImportParseLogic.associateComponentInstanceInterfacesToComponent(
1600             yamlName,
1601             service,
1602             instInterfaces
1603         );
1604         serviceImportParseLogic.associateComponentInstanceInputsToComponent(yamlName, service, instInputs);
1605         serviceImportParseLogic.associateCINodeFilterToComponent(yamlName, service, instNodeFilter);
1606         serviceImportParseLogic.associateDeploymentArtifactsToInstances(user, yamlName, service, instDeploymentArtifacts);
1607         serviceImportParseLogic.associateArtifactsToInstances(yamlName, service, instArtifacts);
1608         serviceImportParseLogic.associateOrAddCalculatedCapReq(yamlName, service, instCapabilities, instRequirements);
1609         log.debug("enter createServiceInstancesRelations test,instRequirements:{},instCapabilities:{}", instRequirements, instCapabilities);
1610         serviceImportParseLogic.associateInstAttributeToComponentToInstances(yamlName, service, instAttributes);
1611         ToscaElement serviceTemplate = ModelConverter.convertToToscaElement(service);
1612         Map<String, ListCapabilityDataDefinition> capabilities = serviceTemplate.getCapabilities();
1613         Map<String, ListRequirementDataDefinition> requirements = serviceTemplate.getRequirements();
1614         serviceImportParseLogic.associateCapabilitiesToService(yamlName, service, capabilities);
1615         serviceImportParseLogic.associateRequirementsToService(yamlName, service, requirements);
1616         service = getResourceAfterCreateRelations(service);
1617         addRelationsToRI(yamlName, service, uploadResInstancesMap, componentInstancesList, relations);
1618         serviceImportParseLogic.associateResourceInstances(yamlName, service, relations);
1619         log.debug("************* in create relations, getResource start");
1620         Either<Service, StorageOperationStatus> eitherGetResource = toscaOperationFacade.getToscaElement(service.getUniqueId());
1621         log.debug("************* in create relations, getResource end");
1622         if (eitherGetResource.isRight()) {
1623             throw new ComponentException(componentsUtils
1624                 .getResponseFormatByComponent(componentsUtils.convertFromStorageResponse(eitherGetResource.right().value()), service,
1625                     service.getComponentType()));
1626         }
1627         return eitherGetResource.left().value();
1628     }
1629
1630     private void updatePropertyToscaFunctionData(final Component service,
1631                                                  final Map<String, List<ComponentInstanceProperty>> instancePropertyMap,
1632                                                  final Map<String, List<AttributeDefinition>> instanceAttributeMap) {
1633         final Component updatedService =
1634             toscaOperationFacade.getToscaElement(service.getUniqueId()).left()
1635                 .on(storageOperationStatus -> {
1636                         final ActionStatus status = componentsUtils.convertFromStorageResponse(storageOperationStatus);
1637                         final ResponseFormat responseFormat =
1638                             componentsUtils.getResponseFormatByComponent(status, service, service.getComponentType());
1639                         throw new ComponentException(responseFormat);
1640                     }
1641                 );
1642         instancePropertyMap.values().forEach(instancePropertyList ->
1643             instancePropertyList.stream()
1644                 .filter(PropertyDataDefinition::isToscaFunction)
1645                 .forEach(instanceProperty -> {
1646                     toscaFunctionService.updateFunctionWithDataFromSelfComponent(instanceProperty.getToscaFunction(),
1647                         updatedService, instancePropertyMap, instanceAttributeMap);
1648                     instanceProperty.setValue(instanceProperty.getToscaFunction().getValue());
1649                 })
1650         );
1651     }
1652
1653     protected void processComponentInstance(String yamlName, Component component, List<ComponentInstance> componentInstancesList,
1654                                             Map<String, DataTypeDefinition> allDataTypes,
1655                                             Map<String, List<ComponentInstanceProperty>> instProperties,
1656                                             Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilties,
1657                                             Map<ComponentInstance, Map<String, List<RequirementDefinition>>> instRequirements,
1658                                             Map<String, Map<String, ArtifactDefinition>> instDeploymentArtifacts,
1659                                             Map<String, Map<String, ArtifactDefinition>> instArtifacts,
1660                                             Map<String, List<AttributeDefinition>> instAttributes, Map<String, Resource> originCompMap,
1661                                             Map<String, List<ComponentInstanceInput>> instInputs,
1662                                             Map<String, UploadNodeFilterInfo> instNodeFilter,
1663                                             Map<String, Map<String, InterfaceDefinition>> instInterfaces,
1664                                             UploadComponentInstanceInfo uploadComponentInstanceInfo) {
1665         log.debug("enter ServiceImportBusinessLogic processComponentInstance");
1666         Optional<ComponentInstance> currentCompInstanceOpt = componentInstancesList.stream()
1667             .filter(i -> i.getName().equals(uploadComponentInstanceInfo.getName())).findFirst();
1668         if (currentCompInstanceOpt.isEmpty()) {
1669             log.debug(COMPONENT_INSTANCE_WITH_NAME_IN_RESOURCE, uploadComponentInstanceInfo.getName(), component.getUniqueId());
1670             BeEcompErrorManager.getInstance()
1671                 .logInternalDataError(COMPONENT_INSTANCE_WITH_NAME + uploadComponentInstanceInfo.getName() + IN_RESOURCE, component.getUniqueId(),
1672                     BeEcompErrorManager.ErrorSeverity.ERROR);
1673             ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
1674             throw new ComponentException(responseFormat);
1675         }
1676         ComponentInstance currentCompInstance = currentCompInstanceOpt.get();
1677         String resourceInstanceId = currentCompInstance.getUniqueId();
1678         Resource originResource = getOriginResource(yamlName, originCompMap, currentCompInstance);
1679         if (MapUtils.isNotEmpty(originResource.getRequirements())) {
1680             instRequirements.put(currentCompInstance, originResource.getRequirements());
1681         }
1682         if (MapUtils.isNotEmpty(originResource.getCapabilities())) {
1683             processComponentInstanceCapabilities(allDataTypes, instCapabilties, uploadComponentInstanceInfo, currentCompInstance, originResource);
1684         }
1685         if (originResource.getDeploymentArtifacts() != null && !originResource.getDeploymentArtifacts().isEmpty()) {
1686             instDeploymentArtifacts.put(resourceInstanceId, originResource.getDeploymentArtifacts());
1687         }
1688         if (originResource.getArtifacts() != null && !originResource.getArtifacts().isEmpty()) {
1689             instArtifacts.put(resourceInstanceId, originResource.getArtifacts());
1690         }
1691         if (originResource.getAttributes() != null && !originResource.getAttributes().isEmpty()) {
1692             instAttributes.put(resourceInstanceId, originResource.getAttributes());
1693             addAttributeValueToResourceInstance(instAttributes, uploadComponentInstanceInfo.getAttributes());
1694         }
1695         if (uploadComponentInstanceInfo.getUploadNodeFilterInfo() != null) {
1696             instNodeFilter.put(resourceInstanceId, uploadComponentInstanceInfo.getUploadNodeFilterInfo());
1697         }
1698         if (MapUtils.isNotEmpty(uploadComponentInstanceInfo.getInterfaces())) {
1699
1700             ResponseFormat addInterfacesToRiRes = addInterfaceValuesToRi(
1701                 uploadComponentInstanceInfo,
1702                 component,
1703                 originResource,
1704                 currentCompInstance,
1705                 instInterfaces
1706             );
1707             if (addInterfacesToRiRes.getStatus() != 200) {
1708                 throw new ComponentException(addInterfacesToRiRes);
1709             }
1710         }
1711         if (originResource.getResourceType() != ResourceTypeEnum.VF) {
1712             ResponseFormat addPropertiesValueToRiRes = addPropertyValuesToRi(uploadComponentInstanceInfo, component, originResource,
1713                 currentCompInstance, instProperties, allDataTypes);
1714             if (addPropertiesValueToRiRes.getStatus() != 200) {
1715                 throw new ComponentException(addPropertiesValueToRiRes);
1716             }
1717         } else {
1718             addInputsValuesToRi(uploadComponentInstanceInfo, component, originResource, currentCompInstance, instInputs, allDataTypes);
1719         }
1720     }
1721
1722     protected void addInputsValuesToRi(UploadComponentInstanceInfo uploadComponentInstanceInfo, Component component, Resource originResource,
1723                                        ComponentInstance currentCompInstance, Map<String, List<ComponentInstanceInput>> instInputs,
1724                                        Map<String, DataTypeDefinition> allDataTypes) {
1725         Map<String, List<UploadPropInfo>> propMap = uploadComponentInstanceInfo.getProperties();
1726         try {
1727             if (MapUtils.isNotEmpty(propMap)) {
1728                 Map<String, InputDefinition> currPropertiesMap = new HashMap<>();
1729                 List<ComponentInstanceInput> instPropList = new ArrayList<>();
1730                 if (CollectionUtils.isEmpty(originResource.getInputs())) {
1731                     log.debug("failed to find properties ");
1732                     throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND));
1733                 }
1734                 originResource.getInputs().forEach(p -> serviceImportParseLogic.addInput(currPropertiesMap, p));
1735                 for (List<UploadPropInfo> propertyList : propMap.values()) {
1736                     processProperty(component, allDataTypes, currPropertiesMap, instPropList, propertyList);
1737                 }
1738                 currPropertiesMap.values().forEach(p -> instPropList.add(new ComponentInstanceInput(p)));
1739                 instInputs.put(currentCompInstance.getUniqueId(), instPropList);
1740             }
1741         } catch (Exception e) {
1742             log.debug("failed to add Inputs Values To Ri");
1743             throw new ComponentException(ActionStatus.GENERAL_ERROR);
1744         }
1745     }
1746
1747     protected void processProperty(Component component, Map<String, DataTypeDefinition> allDataTypes,
1748                                    Map<String, InputDefinition> currPropertiesMap, List<ComponentInstanceInput> instPropList,
1749                                    List<UploadPropInfo> propertyList) {
1750         UploadPropInfo propertyInfo = propertyList.get(0);
1751         String propName = propertyInfo.getName();
1752         if (!currPropertiesMap.containsKey(propName)) {
1753             log.debug("failed to find property {} ", propName);
1754             throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND, propName));
1755         }
1756         processProperty(allDataTypes, currPropertiesMap, instPropList, propertyInfo, propName, component.getInputs());
1757     }
1758
1759     protected void processGetInput(List<GetInputValueDataDefinition> getInputValues, List<InputDefinition> inputs,
1760                                    GetInputValueDataDefinition getInputIndex) {
1761         Optional<InputDefinition> optional;
1762         if (getInputIndex != null) {
1763             optional = inputs.stream().filter(p -> p.getName().equals(getInputIndex.getInputName())).findAny();
1764             if (!optional.isPresent()) {
1765                 log.debug("Failed to find input {} ", getInputIndex.getInputName());
1766                 throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
1767             }
1768             InputDefinition inputIndex = optional.get();
1769             getInputIndex.setInputId(inputIndex.getUniqueId());
1770             getInputValues.add(getInputIndex);
1771         }
1772     }
1773
1774     private void addAttributeValueToResourceInstance(Map<String, List<AttributeDefinition>> instAttributes,
1775                                                      Map<String, UploadAttributeInfo> attributeMap) {
1776         if (attributeMap == null) {
1777             return;
1778         }
1779         attributeMap.forEach((attributeName, attributeValue) -> instAttributes.values()
1780             .forEach(value -> value.stream().filter(attr -> attr.getName().equals(attributeName)).forEach(attr -> {
1781                 if (attributeValue.getValue() instanceof Collection<?> || attributeValue.getValue() instanceof Map<?, ?>) {
1782                     Gson gson = new Gson();
1783                     String json = gson.toJson(attributeValue.getValue());
1784                     attr.setValue(json);
1785                 } else {
1786                     attr.setValue(String.valueOf(attributeValue.getValue()));
1787                 }
1788             })));
1789     }
1790
1791     protected ResponseFormat addPropertyValuesToRi(UploadComponentInstanceInfo uploadComponentInstanceInfo, Component component,
1792                                                    Resource originResource, ComponentInstance currentCompInstance,
1793                                                    Map<String, List<ComponentInstanceProperty>> instProperties,
1794                                                    Map<String, DataTypeDefinition> allDataTypes) {
1795         Map<String, List<UploadPropInfo>> propMap = uploadComponentInstanceInfo.getProperties();
1796         Map<String, PropertyDefinition> currPropertiesMap = new HashMap<>();
1797         List<PropertyDefinition> originalPropertyList = originResource.getProperties();
1798         if (MapUtils.isNotEmpty(propMap) && CollectionUtils.isEmpty(originalPropertyList)) {
1799             log.debug("failed to find properties ");
1800             return componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND);
1801         }
1802         if (CollectionUtils.isEmpty(originalPropertyList)) {
1803             return componentsUtils.getResponseFormat(ActionStatus.OK);
1804         }
1805         originalPropertyList.stream()
1806             .filter(property -> !currPropertiesMap.containsKey(property.getName()))
1807             .forEach(property -> currPropertiesMap.put(property.getName(), property));
1808         List<ComponentInstanceProperty> instPropList = new ArrayList<>();
1809         if (MapUtils.isNotEmpty(propMap)) {
1810             for (final List<UploadPropInfo> propertyList : propMap.values()) {
1811                 UploadPropInfo propertyInfo = propertyList.get(0);
1812                 String propName = propertyInfo.getName();
1813                 if (!currPropertiesMap.containsKey(propName)) {
1814                     log.debug("failed to find property {} ", propName);
1815                     return componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND, propName);
1816                 }
1817                 PropertyDefinition curPropertyDef = currPropertiesMap.get(propName);
1818                 String value = null;
1819                 final List<GetInputValueDataDefinition> getInputs = new ArrayList<>();
1820                 boolean isValidate = true;
1821                 if (propertyInfo.getValue() != null) {
1822                     getInputs.addAll(propertyInfo.getGet_input());
1823                     isValidate = getInputs.isEmpty();
1824                     if (isValidate) {
1825                         value = getPropertyJsonStringValue(propertyInfo.getValue(), curPropertyDef.getType());
1826                     } else {
1827                         value = getPropertyJsonStringValue(propertyInfo.getValue(), TypeUtils.ToscaTagNamesEnum.GET_INPUT.getElementName());
1828                     }
1829                 }
1830                 final var property = new ComponentInstanceProperty(curPropertyDef, value, null);
1831                 String validatePropValue = serviceBusinessLogic.validatePropValueBeforeCreate(property, value, isValidate, allDataTypes);
1832                 property.setValue(validatePropValue);
1833                 property.setToscaFunction(propertyInfo.getToscaFunction());
1834                 if (!getInputs.isEmpty()) {
1835                     final List<GetInputValueDataDefinition> getInputValues = new ArrayList<>();
1836                     for (final GetInputValueDataDefinition getInput : getInputs) {
1837                         final List<InputDefinition> inputs = component.getInputs();
1838                         if (inputs == null || inputs.isEmpty()) {
1839                             log.debug("Failed to add property {} to instance. Inputs list is empty ", property);
1840                             serviceBusinessLogic.rollbackWithException(ActionStatus.INPUTS_NOT_FOUND,
1841                                 property.getGetInputValues().stream().map(GetInputValueDataDefinition::getInputName).collect(toList()).toString());
1842                         }
1843                         InputDefinition input = serviceImportParseLogic.findInputByName(inputs, getInput);
1844                         getInput.setInputId(input.getUniqueId());
1845                         getInputValues.add(getInput);
1846                         GetInputValueDataDefinition getInputIndex = getInput.getGetInputIndex();
1847                         if (getInputIndex != null) {
1848                             input = serviceImportParseLogic.findInputByName(inputs, getInputIndex);
1849                             getInputIndex.setInputId(input.getUniqueId());
1850                             getInputValues.add(getInputIndex);
1851                         }
1852                     }
1853                     property.setGetInputValues(getInputValues);
1854                 }
1855                 instPropList.add(property);
1856                 currPropertiesMap.remove(property.getName());
1857             }
1858         }
1859         if (!currPropertiesMap.isEmpty()) {
1860             for (PropertyDefinition value : currPropertiesMap.values()) {
1861                 instPropList.add(new ComponentInstanceProperty(value));
1862             }
1863         }
1864         instProperties.put(currentCompInstance.getUniqueId(), instPropList);
1865         return componentsUtils.getResponseFormat(ActionStatus.OK);
1866     }
1867
1868     protected ResponseFormat addInterfaceValuesToRi(
1869         UploadComponentInstanceInfo uploadComponentInstanceInfo,
1870         Component component,
1871         Resource originResource, ComponentInstance currentCompInstance,
1872         Map<String, Map<String, InterfaceDefinition>> instInterfaces
1873     ) {
1874         Map<String, UploadInterfaceInfo> instanceInterfacesMap = uploadComponentInstanceInfo.getInterfaces();
1875         Map<String, InterfaceDefinition> currInterfacesMap = new HashMap<>();
1876         Map<String, InterfaceDefinition> interfacesFromNodeType = originResource.getInterfaces();
1877         if ((MapUtils.isNotEmpty(instanceInterfacesMap)) && (MapUtils.isEmpty(interfacesFromNodeType))) {
1878             log.debug("failed to find interfaces ");
1879             return componentsUtils.getResponseFormat(ActionStatus.INTERFACE_NOT_FOUND_IN_COMPONENT);
1880         }
1881         if (interfacesFromNodeType == null || interfacesFromNodeType.isEmpty()) {
1882             return componentsUtils.getResponseFormat(ActionStatus.OK);
1883         }
1884         for (Map.Entry<String, InterfaceDefinition> entryInstances : interfacesFromNodeType.entrySet()) {
1885             String interfaceName = entryInstances.getKey().substring(entryInstances.getKey().lastIndexOf(".") + 1);
1886             if (!currInterfacesMap.containsKey(interfaceName)) {
1887                 currInterfacesMap.put(interfaceName, entryInstances.getValue());
1888             }
1889         }
1890
1891         Map<String, InterfaceDefinition> instInterfacesMap = new HashMap<>();
1892         if (MapUtils.isNotEmpty(instanceInterfacesMap)) {
1893             for (UploadInterfaceInfo uploadInterfaceInfo : instanceInterfacesMap.values()) {
1894                 String interfaceName = uploadInterfaceInfo.getName();
1895                 if (!currInterfacesMap.containsKey(interfaceName)) {
1896                     log.debug("failed to find interface {} ", interfaceName);
1897                     return componentsUtils.getResponseFormat(ActionStatus.INTERFACE_NOT_FOUND_IN_COMPONENT, interfaceName);
1898                 }
1899                 InterfaceDefinition currentInterfaceDef = currInterfacesMap.get(interfaceName);
1900                 Map<String, OperationDataDefinition> operationsToAdd = new HashMap<>();
1901
1902                 Map<String, OperationDataDefinition> operations = uploadInterfaceInfo.getOperations();
1903                 for (Map.Entry<String, OperationDataDefinition> operation : operations.entrySet()) {
1904                     OperationDataDefinition templateOperation = currentInterfaceDef.getOperationsMap().get(operation.getKey());
1905                     OperationDataDefinition instanceOperation = operation.getValue();
1906                     //Inputs
1907                     ListDataDefinition<OperationInputDefinition> instanceInputs = instanceOperation.getInputs();
1908                     mergeOperationInputDefinitions(templateOperation.getInputs(), instanceInputs);
1909                     templateOperation.setInputs(instanceInputs);
1910                     //Implementation
1911                     templateOperation.setImplementation(instanceOperation.getImplementation());
1912                     //Description
1913                     templateOperation.setDescription(instanceOperation.getDescription());
1914                     operationsToAdd.put(operation.getKey(), templateOperation);
1915                 }
1916                 InterfaceDefinition interfaceDef = new InterfaceDefinition();
1917                 interfaceDef.setModel(component.getModel());
1918                 interfaceDef.setType(currentInterfaceDef.getType());
1919                 interfaceDef.setUniqueId(currentInterfaceDef.getType());
1920                 interfaceDef.setDescription(uploadInterfaceInfo.getDescription());
1921                 interfaceDef.setOperations(operationsToAdd);
1922                 instInterfacesMap.put(interfaceName, interfaceDef);
1923                 currInterfacesMap.remove(interfaceName);
1924             }
1925         }
1926         if (!currInterfacesMap.isEmpty()) {
1927             for (InterfaceDefinition value : currInterfacesMap.values()) {
1928                 instInterfacesMap.put(value.getUniqueId(), value);
1929             }
1930         }
1931         instInterfaces.put(currentCompInstance.getUniqueId(), instInterfacesMap);
1932         return componentsUtils.getResponseFormat(ActionStatus.OK);
1933     }
1934
1935     private void mergeOperationInputDefinitions(ListDataDefinition<OperationInputDefinition> inputsFromNodeType,
1936                                                 ListDataDefinition<OperationInputDefinition> instanceInputs) {
1937         instanceInputs.getListToscaDataDefinition().forEach(
1938             instanceInput -> inputsFromNodeType.getListToscaDataDefinition().stream().filter(
1939                 templateInput -> templateInput.getName().equals(instanceInput.getName())
1940             ).forEach(
1941                 newInstanceInput -> {
1942                     instanceInput.setSourceProperty(newInstanceInput.getSourceProperty());
1943                     instanceInput.setSource(newInstanceInput.getSource());
1944                     instanceInput.setType(newInstanceInput.getType());
1945                 }
1946             )
1947         );
1948         instanceInputs.getListToscaDataDefinition().stream()
1949             .filter(instanceInput -> inputsFromNodeType.getListToscaDataDefinition().stream().noneMatch(
1950                 inputFromNodeType -> inputFromNodeType.getName().equals(instanceInput.getName())
1951             ))
1952             .forEach(oldInput -> oldInput.setType("string"));
1953     }
1954
1955     protected void processComponentInstanceCapabilities(Map<String, DataTypeDefinition> allDataTypes,
1956                                                         Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilties,
1957                                                         UploadComponentInstanceInfo uploadComponentInstanceInfo,
1958                                                         ComponentInstance currentCompInstance, Resource originResource) {
1959         log.debug("enter processComponentInstanceCapabilities");
1960         Map<String, List<CapabilityDefinition>> originCapabilities;
1961         if (MapUtils.isNotEmpty(uploadComponentInstanceInfo.getCapabilities())) {
1962             originCapabilities = new HashMap<>();
1963             Map<String, Map<String, UploadPropInfo>> newPropertiesMap = new HashMap<>();
1964             originResource.getCapabilities().forEach((k, v) -> serviceImportParseLogic.addCapabilities(originCapabilities, k, v));
1965             uploadComponentInstanceInfo.getCapabilities().values()
1966                 .forEach(l -> serviceImportParseLogic.addCapabilitiesProperties(newPropertiesMap, l));
1967             updateCapabilityPropertiesValues(allDataTypes, originCapabilities, newPropertiesMap);
1968         } else {
1969             originCapabilities = originResource.getCapabilities();
1970         }
1971         instCapabilties.put(currentCompInstance, originCapabilities);
1972     }
1973
1974     protected void updateCapabilityPropertiesValues(Map<String, DataTypeDefinition> allDataTypes,
1975                                                     Map<String, List<CapabilityDefinition>> originCapabilities,
1976                                                     Map<String, Map<String, UploadPropInfo>> newPropertiesMap) {
1977         originCapabilities.values().stream().flatMap(Collection::stream).filter(c -> newPropertiesMap.containsKey(c.getName()))
1978             .forEach(c -> updatePropertyValues(c.getProperties(), newPropertiesMap.get(c.getName()), allDataTypes));
1979     }
1980
1981     protected void updatePropertyValues(List<ComponentInstanceProperty> properties, Map<String, UploadPropInfo> newProperties,
1982                                         Map<String, DataTypeDefinition> allDataTypes) {
1983         properties.forEach(p -> updatePropertyValue(p, newProperties.get(p.getName()), allDataTypes));
1984     }
1985
1986     protected String updatePropertyValue(ComponentInstanceProperty property, UploadPropInfo propertyInfo,
1987                                          Map<String, DataTypeDefinition> allDataTypes) {
1988         String value = null;
1989         List<GetInputValueDataDefinition> getInputs = null;
1990         boolean isValidate = true;
1991         if (null != propertyInfo && propertyInfo.getValue() != null) {
1992             getInputs = propertyInfo.getGet_input();
1993             isValidate = getInputs == null || getInputs.isEmpty();
1994             if (isValidate) {
1995                 value = getPropertyJsonStringValue(propertyInfo.getValue(), property.getType());
1996             } else {
1997                 value = getPropertyJsonStringValue(propertyInfo.getValue(), TypeUtils.ToscaTagNamesEnum.GET_INPUT.getElementName());
1998             }
1999         }
2000         property.setValue(value);
2001         return serviceBusinessLogic.validatePropValueBeforeCreate(property, value, isValidate, allDataTypes);
2002     }
2003
2004     protected Resource getOriginResource(String yamlName, Map<String, Resource> originCompMap, ComponentInstance currentCompInstance) {
2005         Resource originResource;
2006         log.debug("after enter ServiceImportBusinessLogic processComponentInstance, enter getOriginResource");
2007         if (!originCompMap.containsKey(currentCompInstance.getComponentUid())) {
2008             Either<Resource, StorageOperationStatus> getOriginResourceRes = toscaOperationFacade
2009                 .getToscaFullElement(currentCompInstance.getComponentUid());
2010             if (getOriginResourceRes.isRight()) {
2011                 ResponseFormat responseFormat = componentsUtils
2012                     .getResponseFormat(componentsUtils.convertFromStorageResponse(getOriginResourceRes.right().value()), yamlName);
2013                 throw new ComponentException(responseFormat);
2014             }
2015             originResource = getOriginResourceRes.left().value();
2016             originCompMap.put(originResource.getUniqueId(), originResource);
2017         } else {
2018             originResource = originCompMap.get(currentCompInstance.getComponentUid());
2019         }
2020         return originResource;
2021     }
2022
2023     protected Either<Resource, StorageOperationStatus> updateCalculatedCapReqWithSubstitutionMappings(Resource resource,
2024                                                                                                       Map<String, UploadComponentInstanceInfo> uploadResInstancesMap) {
2025         Either<Resource, StorageOperationStatus> updateRes = null;
2026         Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> updatedInstCapabilities = new HashMap<>();
2027         Map<ComponentInstance, Map<String, List<RequirementDefinition>>> updatedInstRequirements = new HashMap<>();
2028         StorageOperationStatus status = toscaOperationFacade.deleteAllCalculatedCapabilitiesRequirements(resource.getUniqueId());
2029         if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) {
2030             log.debug("Failed to delete all calculated capabilities and requirements of resource {} upon update. Status is {}",
2031                 resource.getUniqueId(), status);
2032             updateRes = Either.right(status);
2033         }
2034         if (updateRes == null) {
2035             fillUpdatedInstCapabilitiesRequirements(resource.getComponentInstances(), uploadResInstancesMap, updatedInstCapabilities,
2036                 updatedInstRequirements);
2037             status = toscaOperationFacade.associateOrAddCalculatedCapReq(updatedInstCapabilities, updatedInstRequirements, resource);
2038             if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) {
2039                 updateRes = Either.right(status);
2040             }
2041         }
2042         if (updateRes == null) {
2043             updateRes = Either.left(resource);
2044         }
2045         return updateRes;
2046     }
2047
2048     protected void fillUpdatedInstCapabilitiesRequirements(List<ComponentInstance> componentInstances,
2049                                                            Map<String, UploadComponentInstanceInfo> uploadResInstancesMap,
2050                                                            Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> updatedInstCapabilities,
2051                                                            Map<ComponentInstance, Map<String, List<RequirementDefinition>>> updatedInstRequirements) {
2052         componentInstances.stream().forEach(i -> {
2053             fillUpdatedInstCapabilities(updatedInstCapabilities, i, uploadResInstancesMap.get(i.getName()).getCapabilitiesNamesToUpdate());
2054             fillUpdatedInstRequirements(updatedInstRequirements, i, uploadResInstancesMap.get(i.getName()).getRequirementsNamesToUpdate());
2055         });
2056     }
2057
2058     protected void fillUpdatedInstCapabilities(Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> updatedInstCapabilties,
2059                                                ComponentInstance instance, Map<String, String> capabilitiesNamesToUpdate) {
2060         Map<String, List<CapabilityDefinition>> updatedCapabilities = new HashMap<>();
2061         Set<String> updatedCapNames = new HashSet<>();
2062         if (MapUtils.isNotEmpty(capabilitiesNamesToUpdate)) {
2063             for (Map.Entry<String, List<CapabilityDefinition>> requirements : instance.getCapabilities().entrySet()) {
2064                 updatedCapabilities.put(requirements.getKey(), requirements.getValue().stream().filter(
2065                         c -> capabilitiesNamesToUpdate.containsKey(c.getName()) && !updatedCapNames.contains(capabilitiesNamesToUpdate.get(c.getName())))
2066                     .map(c -> {
2067                         c.setParentName(c.getName());
2068                         c.setName(capabilitiesNamesToUpdate.get(c.getName()));
2069                         updatedCapNames.add(c.getName());
2070                         return c;
2071                     }).collect(toList()));
2072             }
2073         }
2074         if (MapUtils.isNotEmpty(updatedCapabilities)) {
2075             updatedInstCapabilties.put(instance, updatedCapabilities);
2076         }
2077     }
2078
2079     protected void fillUpdatedInstRequirements(Map<ComponentInstance, Map<String, List<RequirementDefinition>>> updatedInstRequirements,
2080                                                ComponentInstance instance, Map<String, String> requirementsNamesToUpdate) {
2081         Map<String, List<RequirementDefinition>> updatedRequirements = new HashMap<>();
2082         Set<String> updatedReqNames = new HashSet<>();
2083         if (MapUtils.isNotEmpty(requirementsNamesToUpdate)) {
2084             for (Map.Entry<String, List<RequirementDefinition>> requirements : instance.getRequirements().entrySet()) {
2085                 updatedRequirements.put(requirements.getKey(), requirements.getValue().stream().filter(
2086                         r -> requirementsNamesToUpdate.containsKey(r.getName()) && !updatedReqNames.contains(requirementsNamesToUpdate.get(r.getName())))
2087                     .map(r -> {
2088                         r.setParentName(r.getName());
2089                         r.setName(requirementsNamesToUpdate.get(r.getName()));
2090                         updatedReqNames.add(r.getName());
2091                         return r;
2092                     }).collect(toList()));
2093             }
2094         }
2095         if (MapUtils.isNotEmpty(updatedRequirements)) {
2096             updatedInstRequirements.put(instance, updatedRequirements);
2097         }
2098     }
2099
2100     protected void addRelationsToRI(String yamlName, Service service, Map<String, UploadComponentInstanceInfo> uploadResInstancesMap,
2101                                     List<ComponentInstance> componentInstancesList, List<RequirementCapabilityRelDef> relations) {
2102         for (Map.Entry<String, UploadComponentInstanceInfo> entry : uploadResInstancesMap.entrySet()) {
2103             UploadComponentInstanceInfo uploadComponentInstanceInfo = entry.getValue();
2104             ComponentInstance currentCompInstance = null;
2105             for (ComponentInstance compInstance : componentInstancesList) {
2106                 if (compInstance.getName().equals(uploadComponentInstanceInfo.getName())) {
2107                     currentCompInstance = compInstance;
2108                     break;
2109                 }
2110             }
2111             if (currentCompInstance == null) {
2112                 log.debug(COMPONENT_INSTANCE_WITH_NAME_IN_RESOURCE, uploadComponentInstanceInfo.getName(), service.getUniqueId());
2113                 BeEcompErrorManager.getInstance()
2114                     .logInternalDataError(COMPONENT_INSTANCE_WITH_NAME + uploadComponentInstanceInfo.getName() + IN_RESOURCE, service.getUniqueId(),
2115                         BeEcompErrorManager.ErrorSeverity.ERROR);
2116                 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
2117                 throw new ComponentException(responseFormat);
2118             }
2119             ResponseFormat addRelationToRiRes = addRelationToRI(yamlName, service, entry.getValue(), relations);
2120             if (addRelationToRiRes.getStatus() != 200) {
2121                 throw new ComponentException(addRelationToRiRes);
2122             }
2123         }
2124     }
2125
2126     protected ResponseFormat addRelationToRI(String yamlName, Service service, UploadComponentInstanceInfo nodesInfoValue,
2127                                              List<RequirementCapabilityRelDef> relations) {
2128         List<ComponentInstance> componentInstancesList = service.getComponentInstances();
2129         ComponentInstance currentCompInstance = null;
2130         for (ComponentInstance compInstance : componentInstancesList) {
2131             if (compInstance.getName().equals(nodesInfoValue.getName())) {
2132                 currentCompInstance = compInstance;
2133                 break;
2134             }
2135         }
2136         if (currentCompInstance == null) {
2137             log.debug(COMPONENT_INSTANCE_WITH_NAME_IN_RESOURCE, nodesInfoValue.getName(), service.getUniqueId());
2138             BeEcompErrorManager.getInstance()
2139                 .logInternalDataError(COMPONENT_INSTANCE_WITH_NAME + nodesInfoValue.getName() + IN_RESOURCE, service.getUniqueId(),
2140                     BeEcompErrorManager.ErrorSeverity.ERROR);
2141             return componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
2142         }
2143         String resourceInstanceId = currentCompInstance.getUniqueId();
2144         Map<String, List<UploadReqInfo>> regMap = nodesInfoValue.getRequirements();
2145         if (regMap != null) {
2146             Iterator<Map.Entry<String, List<UploadReqInfo>>> nodesRegValue = regMap.entrySet().iterator();
2147             while (nodesRegValue.hasNext()) {
2148                 Map.Entry<String, List<UploadReqInfo>> nodesRegInfoEntry = nodesRegValue.next();
2149                 List<UploadReqInfo> uploadRegInfoList = nodesRegInfoEntry.getValue();
2150                 for (UploadReqInfo uploadRegInfo : uploadRegInfoList) {
2151                     log.debug("Going to create  relation {}", uploadRegInfo.getName());
2152                     String regName = uploadRegInfo.getName();
2153                     RequirementCapabilityRelDef regCapRelDef = new RequirementCapabilityRelDef();
2154                     regCapRelDef.setFromNode(resourceInstanceId);
2155                     log.debug("try to find available requirement {} ", regName);
2156                     Either<RequirementDefinition, ResponseFormat> eitherReqStatus = serviceImportParseLogic
2157                         .findAvailableRequirement(regName, yamlName, nodesInfoValue, currentCompInstance, uploadRegInfo.getCapabilityName());
2158                     if (eitherReqStatus.isRight()) {
2159                         log.debug("failed to find available requirement {} status is {}", regName, eitherReqStatus.right().value());
2160                         return eitherReqStatus.right().value();
2161                     }
2162                     RequirementDefinition validReq = eitherReqStatus.left().value();
2163                     List<CapabilityRequirementRelationship> reqAndRelationshipPairList = regCapRelDef.getRelationships();
2164                     if (reqAndRelationshipPairList == null) {
2165                         reqAndRelationshipPairList = new ArrayList<>();
2166                     }
2167                     RelationshipInfo reqAndRelationshipPair = new RelationshipInfo();
2168                     reqAndRelationshipPair.setRequirement(regName);
2169                     reqAndRelationshipPair.setRequirementOwnerId(validReq.getOwnerId());
2170                     reqAndRelationshipPair.setRequirementUid(validReq.getUniqueId());
2171                     RelationshipImpl relationship = new RelationshipImpl();
2172                     relationship.setType(validReq.getCapability());
2173                     reqAndRelationshipPair.setRelationships(relationship);
2174                     ComponentInstance currentCapCompInstance = null;
2175                     for (ComponentInstance compInstance : componentInstancesList) {
2176                         if (compInstance.getName().equals(uploadRegInfo.getNode())) {
2177                             currentCapCompInstance = compInstance;
2178                             break;
2179                         }
2180                     }
2181                     if (currentCapCompInstance == null) {
2182                         log.debug("The component instance  with name {} not found on resource {} ", uploadRegInfo.getNode(), service.getUniqueId());
2183                         BeEcompErrorManager.getInstance()
2184                             .logInternalDataError(COMPONENT_INSTANCE_WITH_NAME + uploadRegInfo.getNode() + IN_RESOURCE, service.getUniqueId(),
2185                                 BeEcompErrorManager.ErrorSeverity.ERROR);
2186                         return componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
2187                     }
2188                     regCapRelDef.setToNode(currentCapCompInstance.getUniqueId());
2189                     log.debug("try to find aviable Capability  req name is {} ", validReq.getName());
2190                     CapabilityDefinition aviableCapForRel = serviceImportParseLogic
2191                         .findAvailableCapabilityByTypeOrName(validReq, currentCapCompInstance, uploadRegInfo);
2192                     if (aviableCapForRel == null) {
2193                         BeEcompErrorManager.getInstance().logInternalDataError(
2194                             "aviable capability was not found. req name is " + validReq.getName() + " component instance is " + currentCapCompInstance
2195                                 .getUniqueId(), service.getUniqueId(), BeEcompErrorManager.ErrorSeverity.ERROR);
2196                         return componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
2197                     }
2198                     reqAndRelationshipPair.setCapability(aviableCapForRel.getName());
2199                     reqAndRelationshipPair.setCapabilityUid(aviableCapForRel.getUniqueId());
2200                     reqAndRelationshipPair.setCapabilityOwnerId(aviableCapForRel.getOwnerId());
2201                     CapabilityRequirementRelationship capReqRel = new CapabilityRequirementRelationship();
2202                     capReqRel.setRelation(reqAndRelationshipPair);
2203                     if (StringUtils.isNotEmpty(uploadRegInfo.getRelationshipTemplate())) {
2204                         capReqRel.setOperations(getOperations(nodesInfoValue.getOperations(), uploadRegInfo.getRelationshipTemplate()));
2205                     }
2206                     reqAndRelationshipPairList.add(capReqRel);
2207                     regCapRelDef.setRelationships(reqAndRelationshipPairList);
2208                     relations.add(regCapRelDef);
2209                 }
2210             }
2211         }
2212         return componentsUtils.getResponseFormat(ActionStatus.OK, yamlName);
2213     }
2214
2215     private List<OperationUi> getOperations(final Map<String, List<OperationUi>> operations, final String relationshipTemplate) {
2216         final List<OperationUi> operationUiList = new ArrayList<>();
2217         operations.forEach((operationKey, operationValues) -> {
2218             if (operationKey.equals(relationshipTemplate)) {
2219                 operationUiList.addAll(operationValues);
2220             }
2221         });
2222         return operationUiList;
2223     }
2224
2225     protected Service getResourceAfterCreateRelations(Service service) {
2226         ComponentParametersView parametersView = serviceImportParseLogic.getComponentFilterAfterCreateRelations();
2227         Either<Service, StorageOperationStatus> eitherGetResource = toscaOperationFacade.getToscaElement(service.getUniqueId(), parametersView);
2228         if (eitherGetResource.isRight()) {
2229             serviceImportParseLogic.throwComponentExceptionByResource(eitherGetResource.right().value(), service);
2230         }
2231         return eitherGetResource.left().value();
2232     }
2233
2234     protected Service createServiceInstances(String yamlName, Service service, Map<String, UploadComponentInstanceInfo> uploadResInstancesMap,
2235                                              Map<String, Resource> nodeNamespaceMap) {
2236         Either<Resource, ResponseFormat> eitherResource = null;
2237         log.debug("createResourceInstances is {} - going to create resource instanse from CSAR", yamlName);
2238         if (MapUtils.isEmpty(uploadResInstancesMap)) { // PNF can have no resource instances
2239             ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE);
2240             throw new ComponentException(responseFormat);
2241         }
2242         Map<String, Resource> existingNodeTypeMap = new HashMap<>();
2243         if (MapUtils.isNotEmpty(nodeNamespaceMap)) {
2244             nodeNamespaceMap.forEach((k, v) -> existingNodeTypeMap.put(v.getToscaResourceName(), v));
2245         }
2246         Map<ComponentInstance, Resource> resourcesInstancesMap = new HashMap<>();
2247         uploadResInstancesMap.values()
2248             .forEach(i -> createAndAddResourceInstance(i, yamlName, service, nodeNamespaceMap, existingNodeTypeMap, resourcesInstancesMap));
2249         if (MapUtils.isNotEmpty(resourcesInstancesMap)) {
2250             try {
2251                 toscaOperationFacade.associateComponentInstancesToComponent(service, resourcesInstancesMap, false, false);
2252             } catch (StorageException exp) {
2253                 if (exp.getStorageOperationStatus() != null && exp.getStorageOperationStatus() != StorageOperationStatus.OK) {
2254                     log.debug("Failed to add component instances to container component {}", service.getName());
2255                     ResponseFormat responseFormat = componentsUtils
2256                         .getResponseFormat(componentsUtils.convertFromStorageResponse(exp.getStorageOperationStatus()));
2257                     eitherResource = Either.right(responseFormat);
2258                     throw new ComponentException(eitherResource.right().value());
2259                 }
2260             }
2261         }
2262         Either<Service, StorageOperationStatus> eitherGetResource = toscaOperationFacade
2263             .getToscaElement(service.getUniqueId(), serviceImportParseLogic.getComponentWithInstancesFilter());
2264         log.debug("*************finished to get resource {}", service.getUniqueId());
2265         if (eitherGetResource.isRight()) {
2266             ResponseFormat responseFormat = componentsUtils
2267                 .getResponseFormatByComponent(componentsUtils.convertFromStorageResponse(eitherGetResource.right().value()), service,
2268                     ComponentTypeEnum.SERVICE);
2269             throw new ComponentException(responseFormat);
2270         }
2271         if (CollectionUtils.isEmpty(eitherGetResource.left().value().getComponentInstances())) { // PNF can have no resource instances
2272             log.debug("Error when create resource instance from csar. ComponentInstances list empty");
2273             BeEcompErrorManager.getInstance().logBeDaoSystemError("Error when create resource instance from csar. ComponentInstances list empty");
2274             throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE));
2275         }
2276         return eitherGetResource.left().value();
2277     }
2278
2279     protected void createAndAddResourceInstance(UploadComponentInstanceInfo uploadComponentInstanceInfo, String yamlName, Component component,
2280                                                 Map<String, Resource> nodeNamespaceMap, Map<String, Resource> existingnodeTypeMap,
2281                                                 Map<ComponentInstance, Resource> resourcesInstancesMap) {
2282         log.debug("*************Going to create  resource instances {}", uploadComponentInstanceInfo.getName());
2283         try {
2284             if (nodeNamespaceMap.containsKey(uploadComponentInstanceInfo.getType())) {
2285                 uploadComponentInstanceInfo.setType(nodeNamespaceMap.get(uploadComponentInstanceInfo.getType()).getToscaResourceName());
2286             }
2287             Resource refResource = validateResourceInstanceBeforeCreate(yamlName, uploadComponentInstanceInfo, existingnodeTypeMap);
2288             ComponentInstance componentInstance = new ComponentInstance();
2289             componentInstance.setComponentUid(refResource.getUniqueId());
2290             Collection<String> directives = uploadComponentInstanceInfo.getDirectives();
2291             if (directives != null && !directives.isEmpty()) {
2292                 componentInstance.setDirectives(new ArrayList<>(directives));
2293             }
2294             UploadNodeFilterInfo uploadNodeFilterInfo = uploadComponentInstanceInfo.getUploadNodeFilterInfo();
2295             if (uploadNodeFilterInfo != null) {
2296                 componentInstance
2297                     .setNodeFilter(new CINodeFilterUtils().getNodeFilterDataDefinition(uploadNodeFilterInfo, componentInstance.getUniqueId()));
2298             }
2299             ComponentTypeEnum containerComponentType = component.getComponentType();
2300             NodeTypeEnum containerNodeType = containerComponentType.getNodeType();
2301             if (containerNodeType.equals(NodeTypeEnum.Resource) && MapUtils.isNotEmpty(uploadComponentInstanceInfo.getCapabilities()) && MapUtils
2302                 .isNotEmpty(refResource.getCapabilities())) {
2303                 serviceImportParseLogic.setCapabilityNamesTypes(refResource.getCapabilities(), uploadComponentInstanceInfo.getCapabilities());
2304                 Map<String, List<CapabilityDefinition>> validComponentInstanceCapabilities = serviceImportParseLogic
2305                     .getValidComponentInstanceCapabilities(refResource.getUniqueId(), refResource.getCapabilities(),
2306                         uploadComponentInstanceInfo.getCapabilities());
2307                 componentInstance.setCapabilities(validComponentInstanceCapabilities);
2308             }
2309             if (!existingnodeTypeMap.containsKey(uploadComponentInstanceInfo.getType())) {
2310                 ResponseFormat responseFormat = componentsUtils
2311                     .getResponseFormat(ActionStatus.INVALID_NODE_TEMPLATE, yamlName, uploadComponentInstanceInfo.getName(),
2312                         uploadComponentInstanceInfo.getType());
2313                 throw new ComponentException(responseFormat);
2314             }
2315             Resource origResource = existingnodeTypeMap.get(uploadComponentInstanceInfo.getType());
2316             componentInstance.setName(uploadComponentInstanceInfo.getName());
2317             componentInstance.setIcon(origResource.getIcon());
2318             resourcesInstancesMap.put(componentInstance, origResource);
2319         } catch (Exception e) {
2320             throw new ComponentException(ActionStatus.GENERAL_ERROR, e.getMessage());
2321         }
2322     }
2323
2324     protected Resource validateResourceInstanceBeforeCreate(String yamlName, UploadComponentInstanceInfo uploadComponentInstanceInfo,
2325                                                             Map<String, Resource> nodeNamespaceMap) {
2326         Resource refResource;
2327         try {
2328             if (nodeNamespaceMap.containsKey(uploadComponentInstanceInfo.getType())) {
2329                 refResource = nodeNamespaceMap.get(uploadComponentInstanceInfo.getType());
2330             } else {
2331                 Either<Resource, StorageOperationStatus> findResourceEither = toscaOperationFacade
2332                     .getLatestResourceByToscaResourceName(uploadComponentInstanceInfo.getType());
2333                 if (findResourceEither.isRight()) {
2334                     ResponseFormat responseFormat = componentsUtils
2335                         .getResponseFormat(componentsUtils.convertFromStorageResponse(findResourceEither.right().value()));
2336                     throw new ComponentException(responseFormat);
2337                 }
2338                 refResource = findResourceEither.left().value();
2339                 nodeNamespaceMap.put(refResource.getToscaResourceName(), refResource);
2340             }
2341             String componentState = refResource.getComponentMetadataDefinition().getMetadataDataDefinition().getState();
2342             if (componentState.equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
2343                 ResponseFormat responseFormat = componentsUtils
2344                     .getResponseFormat(ActionStatus.ILLEGAL_COMPONENT_STATE, refResource.getComponentType().getValue(), refResource.getName(),
2345                         componentState);
2346                 throw new ComponentException(responseFormat);
2347             }
2348             if (!ModelConverter.isAtomicComponent(refResource) && refResource.getResourceType() != ResourceTypeEnum.VF) {
2349                 log.debug("validateResourceInstanceBeforeCreate -  ref resource type is  ", refResource.getResourceType());
2350                 ResponseFormat responseFormat = componentsUtils
2351                     .getResponseFormat(ActionStatus.INVALID_NODE_TEMPLATE, yamlName, uploadComponentInstanceInfo.getName(),
2352                         uploadComponentInstanceInfo.getType());
2353                 throw new ComponentException(responseFormat);
2354             }
2355             return refResource;
2356         } catch (Exception e) {
2357             throw new ComponentException(ActionStatus.GENERAL_ERROR, e.getMessage());
2358         }
2359     }
2360
2361     protected void handleServiceNodeTypes(String yamlName, Service service, String topologyTemplateYaml, boolean needLock,
2362                                           Map<String, EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle,
2363                                           List<ArtifactDefinition> nodeTypesNewCreatedArtifacts, Map<String, NodeTypeInfo> nodeTypesInfo,
2364                                           CsarInfo csarInfo, String nodeName) {
2365         try {
2366             for (Map.Entry<String, NodeTypeInfo> nodeTypeEntry : nodeTypesInfo.entrySet()) {
2367                 boolean isResourceNotExisted = validateResourceNotExisted(nodeTypeEntry.getKey());
2368                 if (nodeTypeEntry.getValue().isNested() && isResourceNotExisted) {
2369                     handleNestedVF(service, nodeTypesArtifactsToHandle, nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo,
2370                         nodeTypeEntry.getKey());
2371                     log.trace("************* finished to create node {}", nodeTypeEntry.getKey());
2372                 }
2373             }
2374             Map<String, Object> mappedToscaTemplate = null;
2375             if (org.apache.commons.lang.StringUtils.isNotEmpty(nodeName) && MapUtils.isNotEmpty(nodeTypesInfo) && nodeTypesInfo
2376                 .containsKey(nodeName)) {
2377                 mappedToscaTemplate = nodeTypesInfo.get(nodeName).getMappedToscaTemplate();
2378             }
2379             if (MapUtils.isEmpty(mappedToscaTemplate)) {
2380                 mappedToscaTemplate = (Map<String, Object>) new Yaml().load(topologyTemplateYaml);
2381             }
2382             createResourcesFromYamlNodeTypesList(yamlName, service, mappedToscaTemplate, needLock, nodeTypesArtifactsToHandle,
2383                 nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo);
2384         } catch (ComponentException | StorageException e) {
2385             throw e;
2386         } catch (Exception e) {
2387             log.debug("Exception occured when handleServiceNodeTypes, error is:{}", e.getMessage(), e);
2388             throw new ComponentException(ActionStatus.GENERAL_ERROR);
2389         }
2390     }
2391
2392     protected boolean validateResourceNotExisted(String type) {
2393         try {
2394             Either<Resource, StorageOperationStatus> latestResource = toscaOperationFacade.getLatestResourceByToscaResourceName(type);
2395             return latestResource.isRight();
2396         } catch (Exception e) {
2397             log.debug("Exception occured when validateResourceNotExisted, error is:{}", e.getMessage(), e);
2398             throw new ComponentException(ActionStatus.GENERAL_ERROR);
2399         }
2400     }
2401
2402     protected Resource handleNestedVF(Service service,
2403                                       Map<String, EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>>> nodesArtifactsToHandle,
2404                                       List<ArtifactDefinition> createdArtifacts, Map<String, NodeTypeInfo> nodesInfo, CsarInfo csarInfo,
2405                                       String nodeName) {
2406         try {
2407             String yamlName = nodesInfo.get(nodeName).getTemplateFileName();
2408             Map<String, Object> nestedVfcJsonMap = nodesInfo.get(nodeName).getMappedToscaTemplate();
2409             createResourcesFromYamlNodeTypesList(yamlName, service, nestedVfcJsonMap, false, nodesArtifactsToHandle, createdArtifacts, nodesInfo,
2410                 csarInfo);
2411             log.debug("************* Finished to create node types from yaml {}", yamlName);
2412             if (nestedVfcJsonMap.containsKey(TypeUtils.ToscaTagNamesEnum.TOPOLOGY_TEMPLATE.getElementName())) {
2413                 log.debug("************* Going to handle complex VFC from yaml {}", yamlName);
2414                 return handleComplexVfc(nodesArtifactsToHandle, createdArtifacts, nodesInfo, csarInfo, nodeName, yamlName);
2415             }
2416             return new Resource();
2417         } catch (Exception e) {
2418             log.debug("Exception occured when handleNestedVF, error is:{}", e.getMessage(), e);
2419             throw new ComponentException(ActionStatus.GENERAL_ERROR);
2420         }
2421     }
2422
2423     protected Resource handleComplexVfc(
2424         Map<String, EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>>> nodesArtifactsToHandle,
2425         List<ArtifactDefinition> createdArtifacts, Map<String, NodeTypeInfo> nodesInfo, CsarInfo csarInfo, String nodeName, String yamlName) {
2426         try {
2427             Resource oldComplexVfc = null;
2428             Resource newComplexVfc = serviceImportParseLogic.buildValidComplexVfc(csarInfo, nodeName, nodesInfo);
2429             Either<Resource, StorageOperationStatus> oldComplexVfcRes = toscaOperationFacade
2430                 .getFullLatestComponentByToscaResourceName(newComplexVfc.getToscaResourceName());
2431             if (oldComplexVfcRes.isRight() && oldComplexVfcRes.right().value() == StorageOperationStatus.NOT_FOUND) {
2432                 oldComplexVfcRes = toscaOperationFacade.getFullLatestComponentByToscaResourceName(
2433                     serviceImportParseLogic.buildNestedToscaResourceName(ResourceTypeEnum.VF.name(), csarInfo.getVfResourceName(), nodeName)
2434                         .getRight());
2435             }
2436             if (oldComplexVfcRes.isRight() && oldComplexVfcRes.right().value() != StorageOperationStatus.NOT_FOUND) {
2437                 log.debug("Failed to fetch previous complex VFC by tosca resource name {}. Status is {}. ", newComplexVfc.getToscaResourceName(),
2438                     oldComplexVfcRes.right().value());
2439                 throw new ComponentException(ActionStatus.GENERAL_ERROR);
2440             } else if (oldComplexVfcRes.isLeft()) {
2441                 log.debug(VALIDATE_DERIVED_BEFORE_UPDATE);
2442                 Either<Boolean, ResponseFormat> eitherValidation = serviceImportParseLogic
2443                     .validateNestedDerivedFromDuringUpdate(oldComplexVfcRes.left().value(), newComplexVfc,
2444                         ValidationUtils.hasBeenCertified(oldComplexVfcRes.left().value().getVersion()));
2445                 if (eitherValidation.isLeft()) {
2446                     oldComplexVfc = oldComplexVfcRes.left().value();
2447                 }
2448             }
2449             newComplexVfc = handleComplexVfc(nodesArtifactsToHandle, createdArtifacts, nodesInfo, csarInfo, nodeName, yamlName, oldComplexVfc,
2450                 newComplexVfc);
2451             csarInfo.getCreatedNodesToscaResourceNames().put(nodeName, newComplexVfc.getToscaResourceName());
2452             LifecycleChangeInfoWithAction lifecycleChangeInfo = new LifecycleChangeInfoWithAction(CERTIFICATION_ON_IMPORT,
2453                 LifecycleChangeInfoWithAction.LifecycleChanceActionEnum.CREATE_FROM_CSAR);
2454             log.debug("Going to certify cvfc {}. ", newComplexVfc.getName());
2455             final Resource result = serviceImportParseLogic
2456                 .propagateStateToCertified(csarInfo.getModifier(), newComplexVfc, lifecycleChangeInfo, true, false, true);
2457             csarInfo.getCreatedNodes().put(nodeName, result);
2458             csarInfo.removeNodeFromQueue();
2459             return result;
2460         } catch (Exception e) {
2461             log.debug("Exception occured when handleComplexVfc, error is:{}", e.getMessage(), e);
2462             throw new ComponentException(ActionStatus.GENERAL_ERROR);
2463         }
2464     }
2465
2466     protected Resource handleComplexVfc(
2467         Map<String, EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>>> nodesArtifactsToHandle,
2468         List<ArtifactDefinition> createdArtifacts, Map<String, NodeTypeInfo> nodesInfo, CsarInfo csarInfo, String nodeName, String yamlName,
2469         Resource oldComplexVfc, Resource newComplexVfc) {
2470         Resource handleComplexVfcRes;
2471         try {
2472             Map<String, Object> mappedToscaTemplate = nodesInfo.get(nodeName).getMappedToscaTemplate();
2473             String yamlContent = new String(csarInfo.getCsar().get(yamlName));
2474             Map<String, NodeTypeInfo> newNodeTypesInfo = nodesInfo.entrySet().stream()
2475                 .collect(toMap(Map.Entry::getKey, e -> e.getValue().getUnmarkedCopy()));
2476             CsarInfo.markNestedVfc(mappedToscaTemplate, newNodeTypesInfo);
2477             if (oldComplexVfc == null) {
2478                 handleComplexVfcRes = createResourceFromYaml(newComplexVfc, yamlContent, yamlName, newNodeTypesInfo, csarInfo, nodesArtifactsToHandle,
2479                     false, true, nodeName);
2480             } else {
2481                 handleComplexVfcRes = updateResourceFromYaml(oldComplexVfc, newComplexVfc, AuditingActionEnum.UPDATE_RESOURCE_METADATA,
2482                     createdArtifacts, yamlContent, yamlName, csarInfo, newNodeTypesInfo, nodesArtifactsToHandle, nodeName, true);
2483             }
2484             return handleComplexVfcRes;
2485         } catch (Exception e) {
2486             log.debug("Exception occured when handleComplexVfc, error is:{}", e.getMessage(), e);
2487             throw new ComponentException(ActionStatus.GENERAL_ERROR);
2488         }
2489     }
2490
2491     protected Resource updateResourceFromYaml(Resource oldRresource, Resource newRresource, AuditingActionEnum actionEnum,
2492                                               List<ArtifactDefinition> createdArtifacts, String yamlFileName, String yamlFileContent,
2493                                               CsarInfo csarInfo, Map<String, NodeTypeInfo> nodeTypesInfo,
2494                                               Map<String, EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle,
2495                                               String nodeName, boolean isNested) {
2496         boolean inTransaction = true;
2497         boolean shouldLock = false;
2498         Resource preparedResource = null;
2499         ParsedToscaYamlInfo uploadComponentInstanceInfoMap = null;
2500         try {
2501             uploadComponentInstanceInfoMap = csarBusinessLogic
2502                 .getParsedToscaYamlInfo(yamlFileContent, yamlFileName, nodeTypesInfo, csarInfo, nodeName, oldRresource);
2503             Map<String, UploadComponentInstanceInfo> instances = uploadComponentInstanceInfoMap.getInstances();
2504             if (MapUtils.isEmpty(instances) && newRresource.getResourceType() != ResourceTypeEnum.PNF) {
2505                 throw new ComponentException(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlFileName);
2506             }
2507             preparedResource = updateExistingResourceByImport(newRresource, oldRresource, csarInfo.getModifier(), inTransaction, shouldLock,
2508                 isNested).left;
2509             log.trace("YAML topology file found in CSAR, file name: {}, contents: {}", yamlFileName, yamlFileContent);
2510             serviceImportParseLogic.handleResourceGenericType(preparedResource);
2511             handleNodeTypes(yamlFileName, preparedResource, yamlFileContent, shouldLock, nodeTypesArtifactsToHandle, createdArtifacts, nodeTypesInfo,
2512                 csarInfo, nodeName);
2513             preparedResource = serviceImportParseLogic.createInputsOnResource(preparedResource, uploadComponentInstanceInfoMap.getInputs());
2514             preparedResource = createResourceInstances(yamlFileName, preparedResource, instances, csarInfo.getCreatedNodes());
2515             preparedResource = createResourceInstancesRelations(csarInfo.getModifier(), yamlFileName, preparedResource, instances);
2516         } catch (ComponentException e) {
2517             ResponseFormat responseFormat =
2518                 e.getResponseFormat() == null ? componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams()) : e.getResponseFormat();
2519             log.debug("#updateResourceFromYaml - failed to update resource from yaml {} .The error is {}", yamlFileName, responseFormat);
2520             componentsUtils
2521                 .auditResource(responseFormat, csarInfo.getModifier(), preparedResource == null ? oldRresource : preparedResource, actionEnum);
2522             throw e;
2523         } catch (StorageException e) {
2524             ResponseFormat responseFormat = componentsUtils
2525                 .getResponseFormat(componentsUtils.convertFromStorageResponse(e.getStorageOperationStatus()));
2526             log.debug("#updateResourceFromYaml - failed to update resource from yaml {} .The error is {}", yamlFileName, responseFormat);
2527             componentsUtils
2528                 .auditResource(responseFormat, csarInfo.getModifier(), preparedResource == null ? oldRresource : preparedResource, actionEnum);
2529             throw e;
2530         }
2531         Either<Map<String, GroupDefinition>, ResponseFormat> validateUpdateVfGroupNamesRes = groupBusinessLogic.validateUpdateVfGroupNames(
2532             uploadComponentInstanceInfoMap.getGroups(), preparedResource.getSystemName());
2533         if (validateUpdateVfGroupNamesRes.isRight()) {
2534             throw new ComponentException(validateUpdateVfGroupNamesRes.right().value());
2535         }
2536         Map<String, GroupDefinition> groups;
2537         if (!validateUpdateVfGroupNamesRes.left().value().isEmpty()) {
2538             groups = validateUpdateVfGroupNamesRes.left().value();
2539         } else {
2540             groups = uploadComponentInstanceInfoMap.getGroups();
2541         }
2542         serviceImportParseLogic.handleGroupsProperties(preparedResource, groups);
2543         preparedResource = serviceImportParseLogic.updateGroupsOnResource(preparedResource, groups);
2544         NodeTypeInfoToUpdateArtifacts nodeTypeInfoToUpdateArtifacts = new NodeTypeInfoToUpdateArtifacts(nodeName, nodeTypesArtifactsToHandle);
2545         Either<Resource, ResponseFormat> updateArtifactsEither = createOrUpdateArtifacts(ArtifactsBusinessLogic.ArtifactOperationEnum.UPDATE,
2546             createdArtifacts, yamlFileName, csarInfo, preparedResource, nodeTypeInfoToUpdateArtifacts, inTransaction, shouldLock);
2547         if (updateArtifactsEither.isRight()) {
2548             log.debug("failed to update artifacts {}", updateArtifactsEither.right().value());
2549             throw new ComponentException(updateArtifactsEither.right().value());
2550         }
2551         preparedResource = serviceImportParseLogic.getResourceWithGroups(updateArtifactsEither.left().value().getUniqueId());
2552         ActionStatus mergingPropsAndInputsStatus = resourceDataMergeBusinessLogic.mergeResourceEntities(oldRresource, preparedResource);
2553         if (mergingPropsAndInputsStatus != ActionStatus.OK) {
2554             ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(mergingPropsAndInputsStatus, preparedResource);
2555             throw new ComponentException(responseFormat);
2556         }
2557         compositionBusinessLogic.setPositionsForComponentInstances(preparedResource, csarInfo.getModifier().getUserId());
2558         return preparedResource;
2559     }
2560
2561     protected Resource createResourceFromYaml(Resource resource, String topologyTemplateYaml, String yamlName,
2562                                               Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo,
2563                                               Map<String, EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToCreate,
2564                                               boolean shouldLock, boolean inTransaction, String nodeName) {
2565         List<ArtifactDefinition> createdArtifacts = new ArrayList<>();
2566         Resource createdResource;
2567         try {
2568             ParsedToscaYamlInfo parsedToscaYamlInfo = csarBusinessLogic
2569                 .getParsedToscaYamlInfo(topologyTemplateYaml, yamlName, nodeTypesInfo, csarInfo, nodeName, resource);
2570             if (MapUtils.isEmpty(parsedToscaYamlInfo.getInstances()) && resource.getResourceType() != ResourceTypeEnum.PNF) {
2571                 throw new ComponentException(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
2572             }
2573             log.debug("#createResourceFromYaml - Going to create resource {} and RIs ", resource.getName());
2574             createdResource = createResourceAndRIsFromYaml(yamlName, resource, parsedToscaYamlInfo, AuditingActionEnum.IMPORT_RESOURCE, false,
2575                 createdArtifacts, topologyTemplateYaml, nodeTypesInfo, csarInfo, nodeTypesArtifactsToCreate, shouldLock, inTransaction, nodeName);
2576             log.debug("#createResourceFromYaml - The resource {} has been created ", resource.getName());
2577         } catch (ComponentException e) {
2578             ResponseFormat responseFormat =
2579                 e.getResponseFormat() == null ? componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams()) : e.getResponseFormat();
2580             componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, AuditingActionEnum.IMPORT_RESOURCE);
2581             throw e;
2582         } catch (StorageException e) {
2583             ResponseFormat responseFormat = componentsUtils
2584                 .getResponseFormat(componentsUtils.convertFromStorageResponse(e.getStorageOperationStatus()));
2585             componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, AuditingActionEnum.IMPORT_RESOURCE);
2586             throw e;
2587         }
2588         return createdResource;
2589     }
2590
2591     protected Resource createResourceAndRIsFromYaml(String yamlName, Resource resource, ParsedToscaYamlInfo parsedToscaYamlInfo,
2592                                                     AuditingActionEnum actionEnum, boolean isNormative, List<ArtifactDefinition> createdArtifacts,
2593                                                     String topologyTemplateYaml, Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo,
2594                                                     Map<String, EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToCreate,
2595                                                     boolean shouldLock, boolean inTransaction, String nodeName) {
2596         List<ArtifactDefinition> nodeTypesNewCreatedArtifacts = new ArrayList<>();
2597         if (shouldLock) {
2598             Either<Boolean, ResponseFormat> lockResult = serviceBusinessLogic
2599                 .lockComponentByName(resource.getSystemName(), resource, CREATE_RESOURCE);
2600             if (lockResult.isRight()) {
2601                 serviceImportParseLogic.rollback(inTransaction, resource, createdArtifacts, nodeTypesNewCreatedArtifacts);
2602                 throw new ComponentException(lockResult.right().value());
2603             }
2604             log.debug("name is locked {} status = {}", resource.getSystemName(), lockResult);
2605         }
2606         try {
2607             log.trace("************* createResourceFromYaml before full create resource {}", yamlName);
2608             Resource genericResource = serviceBusinessLogic.fetchAndSetDerivedFromGenericType(resource);
2609             resource = createResourceTransaction(resource, csarInfo.getModifier(), isNormative);
2610             log.trace("************* Going to add inputs from yaml {}", yamlName);
2611             Map<String, Object> yamlMap = ImportUtils.loadYamlAsStrictMap(csarInfo.getMainTemplateContent());
2612             Map<String, Object> metadata = (Map<String, Object>) yamlMap.get("metadata");
2613             String type = (String) metadata.get("type");
2614             if (resource.shouldGenerateInputs() && !"Service".equalsIgnoreCase(type)) {
2615                 serviceBusinessLogic.generateAndAddInputsFromGenericTypeProperties(resource, genericResource);
2616             }
2617             Map<String, InputDefinition> inputs = parsedToscaYamlInfo.getInputs();
2618             resource = serviceImportParseLogic.createInputsOnResource(resource, inputs);
2619             Map<String, UploadComponentInstanceInfo> uploadComponentInstanceInfoMap = parsedToscaYamlInfo.getInstances();
2620             resource = createRIAndRelationsFromYaml(yamlName, resource, uploadComponentInstanceInfoMap, topologyTemplateYaml,
2621                 nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo, nodeTypesArtifactsToCreate, nodeName);
2622             log.trace("************* Finished to create nodes, RI and Relation  from yaml {}", yamlName);
2623             // validate update vf module group names
2624             Either<Map<String, GroupDefinition>, ResponseFormat> validateUpdateVfGroupNamesRes = groupBusinessLogic.validateUpdateVfGroupNames(
2625                 parsedToscaYamlInfo.getGroups(), resource.getSystemName());
2626             if (validateUpdateVfGroupNamesRes.isRight()) {
2627                 serviceImportParseLogic.rollback(inTransaction, resource, createdArtifacts, nodeTypesNewCreatedArtifacts);
2628                 throw new ComponentException(validateUpdateVfGroupNamesRes.right().value());
2629             }
2630             Map<String, GroupDefinition> groups;
2631             log.trace("************* Going to add groups from yaml {}", yamlName);
2632             if (!validateUpdateVfGroupNamesRes.left().value().isEmpty()) {
2633                 groups = validateUpdateVfGroupNamesRes.left().value();
2634             } else {
2635                 groups = parsedToscaYamlInfo.getGroups();
2636             }
2637             Either<Resource, ResponseFormat> createGroupsOnResource = createGroupsOnResource(resource, groups);
2638             if (createGroupsOnResource.isRight()) {
2639                 serviceImportParseLogic.rollback(inTransaction, resource, createdArtifacts, nodeTypesNewCreatedArtifacts);
2640                 throw new ComponentException(createGroupsOnResource.right().value());
2641             }
2642             resource = createGroupsOnResource.left().value();
2643             log.trace("************* Going to add artifacts from yaml {}", yamlName);
2644             NodeTypeInfoToUpdateArtifacts nodeTypeInfoToUpdateArtifacts = new NodeTypeInfoToUpdateArtifacts(nodeName, nodeTypesArtifactsToCreate);
2645             Either<Resource, ResponseFormat> createArtifactsEither = createOrUpdateArtifacts(ArtifactsBusinessLogic.ArtifactOperationEnum.CREATE,
2646                 createdArtifacts, yamlName, csarInfo, resource, nodeTypeInfoToUpdateArtifacts, inTransaction, shouldLock);
2647             if (createArtifactsEither.isRight()) {
2648                 serviceImportParseLogic.rollback(inTransaction, resource, createdArtifacts, nodeTypesNewCreatedArtifacts);
2649                 throw new ComponentException(createArtifactsEither.right().value());
2650             }
2651             resource = serviceImportParseLogic.getResourceWithGroups(createArtifactsEither.left().value().getUniqueId());
2652             ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.CREATED);
2653             componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, actionEnum);
2654             ASDCKpiApi.countCreatedResourcesKPI();
2655             return resource;
2656         } catch (ComponentException | StorageException e) {
2657             serviceImportParseLogic.rollback(inTransaction, resource, createdArtifacts, nodeTypesNewCreatedArtifacts);
2658             throw e;
2659         } finally {
2660             if (!inTransaction) {
2661                 janusGraphDao.commit();
2662             }
2663             if (shouldLock) {
2664                 graphLockOperation.unlockComponentByName(resource.getSystemName(), resource.getUniqueId(), NodeTypeEnum.Resource);
2665             }
2666         }
2667     }
2668
2669     protected Either<Resource, ResponseFormat> createGroupsOnResource(Resource resource, Map<String, GroupDefinition> groups) {
2670         if (groups != null && !groups.isEmpty()) {
2671             List<GroupDefinition> groupsAsList = updateGroupsMembersUsingResource(groups, resource);
2672             serviceImportParseLogic.handleGroupsProperties(resource, groups);
2673             serviceImportParseLogic.fillGroupsFinalFields(groupsAsList);
2674             Either<List<GroupDefinition>, ResponseFormat> createGroups = groupBusinessLogic.createGroups(resource, groupsAsList, true);
2675             if (createGroups.isRight()) {
2676                 return Either.right(createGroups.right().value());
2677             }
2678         } else {
2679             return Either.left(resource);
2680         }
2681         Either<Resource, StorageOperationStatus> updatedResource = toscaOperationFacade.getToscaElement(resource.getUniqueId());
2682         if (updatedResource.isRight()) {
2683             ResponseFormat responseFormat = componentsUtils
2684                 .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(updatedResource.right().value()), resource);
2685             return Either.right(responseFormat);
2686         }
2687         return Either.left(updatedResource.left().value());
2688     }
2689
2690     protected List<GroupDefinition> updateGroupsMembersUsingResource(Map<String, GroupDefinition> groups, Resource component) {
2691         List<GroupDefinition> result = new ArrayList<>();
2692         List<ComponentInstance> componentInstances = component.getComponentInstances();
2693         if (groups != null) {
2694             for (Map.Entry<String, GroupDefinition> entry : groups.entrySet()) {
2695                 String groupName = entry.getKey();
2696                 GroupDefinition groupDefinition = entry.getValue();
2697                 GroupDefinition updatedGroupDefinition = new GroupDefinition(groupDefinition);
2698                 updatedGroupDefinition.setMembers(null);
2699                 Map<String, String> members = groupDefinition.getMembers();
2700                 if (members != null) {
2701                     updateGroupMembers(groups, updatedGroupDefinition, component, componentInstances, groupName, members);
2702                 }
2703                 result.add(updatedGroupDefinition);
2704             }
2705         }
2706         return result;
2707     }
2708
2709     protected void updateGroupMembers(Map<String, GroupDefinition> groups, GroupDefinition updatedGroupDefinition, Resource component,
2710                                       List<ComponentInstance> componentInstances, String groupName, Map<String, String> members) {
2711         Set<String> compInstancesNames = members.keySet();
2712         if (CollectionUtils.isEmpty(componentInstances)) {
2713             String membersAstString = compInstancesNames.stream().collect(joining(","));
2714             log.debug("The members: {}, in group: {}, cannot be found in component {}. There are no component instances.", membersAstString,
2715                 groupName, component.getNormalizedName());
2716             throw new ComponentException(componentsUtils
2717                 .getResponseFormat(ActionStatus.GROUP_INVALID_COMPONENT_INSTANCE, membersAstString, groupName, component.getNormalizedName(),
2718                     serviceImportParseLogic.getComponentTypeForResponse(component)));
2719         }
2720         Map<String, String> memberNames = componentInstances.stream().collect(toMap(ComponentInstance::getName, ComponentInstance::getUniqueId));
2721         memberNames.putAll(groups.keySet().stream().collect(toMap(g -> g, g -> "")));
2722         Map<String, String> relevantInstances = memberNames.entrySet().stream().filter(n -> compInstancesNames.contains(n.getKey()))
2723             .collect(toMap(Map.Entry::getKey, Map.Entry::getValue));
2724         if (relevantInstances == null || relevantInstances.size() != compInstancesNames.size()) {
2725             List<String> foundMembers = new ArrayList<>();
2726             if (relevantInstances != null) {
2727                 foundMembers = relevantInstances.keySet().stream().collect(toList());
2728             }
2729             compInstancesNames.removeAll(foundMembers);
2730             String membersAstString = compInstancesNames.stream().collect(joining(","));
2731             throw new ComponentException(componentsUtils
2732                 .getResponseFormat(ActionStatus.GROUP_INVALID_COMPONENT_INSTANCE, membersAstString, groupName, component.getNormalizedName(),
2733                     serviceImportParseLogic.getComponentTypeForResponse(component)));
2734         }
2735         updatedGroupDefinition.setMembers(relevantInstances);
2736     }
2737
2738     protected Resource createResourceTransaction(Resource resource, User user, boolean isNormative) {
2739         Either<Boolean, StorageOperationStatus> eitherValidation = toscaOperationFacade
2740             .validateComponentNameExists(resource.getName(), resource.getResourceType(), resource.getComponentType());
2741         if (eitherValidation.isRight()) {
2742             ResponseFormat errorResponse = componentsUtils
2743                 .getResponseFormat(componentsUtils.convertFromStorageResponse(eitherValidation.right().value()));
2744             throw new ComponentException(errorResponse);
2745         }
2746         if (Boolean.TRUE.equals(eitherValidation.left().value())) {
2747             log.debug("resource with name: {}, already exists", resource.getName());
2748             ResponseFormat errorResponse = componentsUtils
2749                 .getResponseFormat(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, ComponentTypeEnum.RESOURCE.getValue(), resource.getName());
2750             throw new ComponentException(errorResponse);
2751         }
2752         log.debug("send resource {} to dao for create", resource.getName());
2753         serviceImportParseLogic.createArtifactsPlaceHolderData(resource, user);
2754         if (!isNormative) {
2755             log.debug("enrich resource with creator, version and state");
2756             resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
2757             resource.setVersion(INITIAL_VERSION);
2758             resource.setHighestVersion(true);
2759             if (resource.getResourceType() != null && resource.getResourceType() != ResourceTypeEnum.VF) {
2760                 resource.setAbstract(false);
2761             }
2762         }
2763         return toscaOperationFacade.createToscaComponent(resource).left()
2764             .on(r -> serviceImportParseLogic.throwComponentExceptionByResource(r, resource));
2765     }
2766
2767     protected ImmutablePair<Resource, ActionStatus> updateExistingResourceByImport(Resource newResource, Resource oldResource, User user,
2768                                                                                    boolean inTransaction, boolean needLock, boolean isNested) {
2769         String lockedResourceId = oldResource.getUniqueId();
2770         log.debug("found resource: name={}, id={}, version={}, state={}", oldResource.getName(), lockedResourceId, oldResource.getVersion(),
2771             oldResource.getLifecycleState());
2772         ImmutablePair<Resource, ActionStatus> resourcePair = null;
2773         try {
2774             serviceBusinessLogic.lockComponent(lockedResourceId, oldResource, needLock, "Update Resource by Import");
2775             oldResource = serviceImportParseLogic.prepareResourceForUpdate(oldResource, newResource, user, inTransaction, false);
2776             serviceImportParseLogic.mergeOldResourceMetadataWithNew(oldResource, newResource);
2777             serviceImportParseLogic.validateResourceFieldsBeforeUpdate(oldResource, newResource, inTransaction, isNested);
2778             serviceImportParseLogic.validateCapabilityTypesCreate(user, serviceImportParseLogic.getCapabilityTypeOperation(), newResource,
2779                 AuditingActionEnum.IMPORT_RESOURCE, inTransaction);
2780             createNewResourceToOldResource(newResource, oldResource, user);
2781             Either<Resource, StorageOperationStatus> overrideResource = toscaOperationFacade.overrideComponent(newResource, oldResource);
2782             if (overrideResource.isRight()) {
2783                 ResponseFormat responseFormat = new ResponseFormat();
2784                 serviceBusinessLogic.throwComponentException(responseFormat);
2785             }
2786             log.debug("Resource updated successfully!!!");
2787             resourcePair = new ImmutablePair<>(overrideResource.left().value(), ActionStatus.OK);
2788             return resourcePair;
2789         } finally {
2790             if (resourcePair == null) {
2791                 BeEcompErrorManager.getInstance().logBeSystemError("Change LifecycleState - Certify");
2792                 janusGraphDao.rollback();
2793             } else if (!inTransaction) {
2794                 janusGraphDao.commit();
2795             }
2796             if (needLock) {
2797                 log.debug("unlock resource {}", lockedResourceId);
2798                 graphLockOperation.unlockComponent(lockedResourceId, NodeTypeEnum.Resource);
2799             }
2800         }
2801     }
2802
2803     protected void createNewResourceToOldResource(Resource newResource, Resource oldResource, User user) {
2804         newResource.setContactId(newResource.getContactId().toLowerCase());
2805         newResource.setCreatorUserId(user.getUserId());
2806         newResource.setCreatorFullName(user.getFullName());
2807         newResource.setLastUpdaterUserId(user.getUserId());
2808         newResource.setLastUpdaterFullName(user.getFullName());
2809         newResource.setUniqueId(oldResource.getUniqueId());
2810         newResource.setVersion(oldResource.getVersion());
2811         newResource.setInvariantUUID(oldResource.getInvariantUUID());
2812         newResource.setLifecycleState(oldResource.getLifecycleState());
2813         newResource.setUUID(oldResource.getUUID());
2814         newResource.setNormalizedName(oldResource.getNormalizedName());
2815         newResource.setSystemName(oldResource.getSystemName());
2816         if (oldResource.getCsarUUID() != null) {
2817             newResource.setCsarUUID(oldResource.getCsarUUID());
2818         }
2819         if (oldResource.getCsarVersionId() != null) {
2820             newResource.setCsarVersionId(oldResource.getCsarVersionId());
2821         }
2822         if (oldResource.getImportedToscaChecksum() != null) {
2823             newResource.setImportedToscaChecksum(oldResource.getImportedToscaChecksum());
2824         }
2825         if (newResource.getDerivedFromGenericType() == null || newResource.getDerivedFromGenericType().isEmpty()) {
2826             newResource.setDerivedFromGenericType(oldResource.getDerivedFromGenericType());
2827         }
2828         if (newResource.getDerivedFromGenericVersion() == null || newResource.getDerivedFromGenericVersion().isEmpty()) {
2829             newResource.setDerivedFromGenericVersion(oldResource.getDerivedFromGenericVersion());
2830         }
2831         if (newResource.getToscaArtifacts() == null || newResource.getToscaArtifacts().isEmpty()) {
2832             serviceBusinessLogic.setToscaArtifactsPlaceHolders(newResource, user);
2833         }
2834         if (newResource.getInterfaces() == null || newResource.getInterfaces().isEmpty()) {
2835             newResource.setInterfaces(oldResource.getInterfaces());
2836         }
2837         if (CollectionUtils.isEmpty(newResource.getProperties())) {
2838             newResource.setProperties(oldResource.getProperties());
2839         }
2840         if (newResource.getModel() == null) {
2841             newResource.setModel(oldResource.getModel());
2842         }
2843     }
2844
2845     protected Map<String, Resource> createResourcesFromYamlNodeTypesList(String yamlName, Service service, Map<String, Object> mappedToscaTemplate,
2846                                                                          boolean needLock,
2847                                                                          Map<String, EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle,
2848                                                                          List<ArtifactDefinition> nodeTypesNewCreatedArtifacts,
2849                                                                          Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo) {
2850         try {
2851             Either<String, ImportUtils.ResultStatusEnum> toscaVersion = findFirstToscaStringElement(mappedToscaTemplate,
2852                 TypeUtils.ToscaTagNamesEnum.TOSCA_VERSION);
2853             if (toscaVersion.isRight()) {
2854                 throw new ComponentException(ActionStatus.INVALID_TOSCA_TEMPLATE);
2855             }
2856             Map<String, Object> mapToConvert = new HashMap<>();
2857             mapToConvert.put(TypeUtils.ToscaTagNamesEnum.TOSCA_VERSION.getElementName(), toscaVersion.left().value());
2858             Map<String, Object> nodeTypes = serviceImportParseLogic.getNodeTypesFromTemplate(mappedToscaTemplate);
2859             createNodeTypes(yamlName, service, needLock, nodeTypesArtifactsToHandle, nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo,
2860                 mapToConvert, nodeTypes);
2861             return csarInfo.getCreatedNodes();
2862         } catch (Exception e) {
2863             log.debug("Exception occured when createResourcesFromYamlNodeTypesList,error is:{}", e.getMessage(), e);
2864             throw new ComponentException(ActionStatus.GENERAL_ERROR);
2865         }
2866     }
2867
2868     protected void createNodeTypes(String yamlName, Service service, boolean needLock,
2869                                    Map<String, EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle,
2870                                    List<ArtifactDefinition> nodeTypesNewCreatedArtifacts, Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo,
2871                                    Map<String, Object> mapToConvert, Map<String, Object> nodeTypes) {
2872         Iterator<Map.Entry<String, Object>> nodesNameValueIter = nodeTypes.entrySet().iterator();
2873         Resource vfcCreated = null;
2874         while (nodesNameValueIter.hasNext()) {
2875             Map.Entry<String, Object> nodeType = nodesNameValueIter.next();
2876             String nodeTypeKey = nodeType.getKey();
2877             Map<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle =
2878                 nodeTypesArtifactsToHandle == null || nodeTypesArtifactsToHandle.isEmpty() ? null : nodeTypesArtifactsToHandle.get(nodeTypeKey);
2879             if (nodeTypesInfo.containsKey(nodeTypeKey)) {
2880                 vfcCreated = handleNestedVfc(service, nodeTypesArtifactsToHandle, nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo,
2881                     nodeTypeKey);
2882                 log.trace("************* Finished to handle nested vfc {}", nodeTypeKey);
2883             } else if (csarInfo.getCreatedNodesToscaResourceNames() != null && !csarInfo.getCreatedNodesToscaResourceNames()
2884                 .containsKey(nodeTypeKey)) {
2885                 ImmutablePair<Resource, ActionStatus> resourceCreated = serviceImportParseLogic
2886                     .createNodeTypeResourceFromYaml(yamlName, nodeType, csarInfo.getModifier(), mapToConvert, service, needLock,
2887                         nodeTypeArtifactsToHandle, nodeTypesNewCreatedArtifacts, true, csarInfo, true);
2888                 log.debug("************* Finished to create node {}", nodeTypeKey);
2889                 vfcCreated = resourceCreated.getLeft();
2890                 csarInfo.getCreatedNodesToscaResourceNames().put(nodeTypeKey, vfcCreated.getName());
2891             }
2892             if (vfcCreated != null) {
2893                 csarInfo.getCreatedNodes().put(nodeTypeKey, vfcCreated);
2894             }
2895             mapToConvert.remove(TypeUtils.ToscaTagNamesEnum.NODE_TYPES.getElementName());
2896         }
2897     }
2898 }