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