Add rollback on import fail
[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, parsedToscaYamlInfo.getSubstitutionMappingProperties());
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.Service);
757             }
758         }
759     }
760
761     private Service updateInputs(final Service component, final String userId, final Map<String, List<String>> substitutionMappingProperties) {
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, substitutionMappingProperties);
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 Map<String, List<String>> substitutionMappingProperties) {
841         final List<PropertyDefinition> properties = component.getProperties();
842         if (CollectionUtils.isNotEmpty(properties) && MapUtils.isNotEmpty(substitutionMappingProperties)) {
843             AtomicReference<String> propertyNameFromInput = new AtomicReference<>(" ");
844             substitutionMappingProperties.entrySet().forEach(stringEntry -> {
845                 if (stringEntry.getValue().get(0).equals(input.getName())) {
846                     propertyNameFromInput.set(stringEntry.getKey());
847                 }
848             });
849
850             final Optional<PropertyDefinition> propDefOptional = properties.stream().filter(prop -> prop.getName().equals(propertyNameFromInput.get()))
851                 .findFirst();
852             if (propDefOptional.isPresent()) {
853                 // From SELF
854                 final String componentUniqueId = component.getUniqueId();
855                 final PropertyDefinition propertyDefinition = propDefOptional.get();
856                 updateProperty(propertyDefinition, input, componentUniqueId);
857                 final JSONObject jsonObject = new JSONObject();
858                 jsonObject.put(ToscaGetFunctionType.GET_INPUT.getFunctionName(), input.getName());
859                 propertyDefinition.setValue(jsonObject.toJSONString());
860                 updateInput(input, propertyDefinition, userId, componentUniqueId);
861
862                 final Either<PropertyDefinition, StorageOperationStatus> either
863                     = toscaOperationFacade.updatePropertyOfComponent(component, propertyDefinition);
864                 if (either.isRight()) {
865                     throw new ComponentException(ActionStatus.GENERAL_ERROR);
866                 }
867             }
868         }
869     }
870
871     private void updateProperty(final PropertyDefinition propertyDefinition, final InputDefinition input, final String componentUniqueId) {
872         propertyDefinition.setParentUniqueId(componentUniqueId);
873         final GetInputValueDataDefinition getInputValueDataDefinition = new GetInputValueDataDefinition();
874         getInputValueDataDefinition.setInputId(input.getUniqueId());
875         getInputValueDataDefinition.setInputName(input.getName());
876         getInputValueDataDefinition.setPropName(propertyDefinition.getName());
877         propertyDefinition.setGetInputValues(Collections.singletonList(getInputValueDataDefinition));
878     }
879
880     private void updateInput(final InputDefinition input, final PropertyDefinition propertyDefinition,
881                              final String userId, final String componentUniqueId) {
882         input.setProperties(Collections.singletonList(new ComponentInstanceProperty(propertyDefinition)));
883         input.setInstanceUniqueId(componentUniqueId);
884         input.setOwnerId(userId);
885         input.setPropertyId(propertyDefinition.getUniqueId());
886         input.setParentPropertyType(propertyDefinition.getType());
887     }
888
889     protected Either<Resource, ResponseFormat> createOrUpdateArtifacts(ArtifactsBusinessLogic.ArtifactOperationEnum operation,
890                                                                        List<ArtifactDefinition> createdArtifacts, String yamlFileName,
891                                                                        CsarInfo csarInfo, Resource preparedResource,
892                                                                        NodeTypeInfoToUpdateArtifacts nodeTypeInfoToUpdateArtifacts,
893                                                                        boolean inTransaction, boolean shouldLock) {
894         String nodeName = nodeTypeInfoToUpdateArtifacts.getNodeName();
895         Resource resource = preparedResource;
896         Map<String, EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle = nodeTypeInfoToUpdateArtifacts
897             .getNodeTypesArtifactsToHandle();
898         if (preparedResource.getResourceType() == ResourceTypeEnum.VF) {
899             if (nodeName != null && nodeTypesArtifactsToHandle.get(nodeName) != null && !nodeTypesArtifactsToHandle.get(nodeName).isEmpty()) {
900                 Either<List<ArtifactDefinition>, ResponseFormat> handleNodeTypeArtifactsRes = handleNodeTypeArtifacts(preparedResource,
901                     nodeTypesArtifactsToHandle.get(nodeName), createdArtifacts, csarInfo.getModifier(), inTransaction, true);
902                 if (handleNodeTypeArtifactsRes.isRight()) {
903                     return Either.right(handleNodeTypeArtifactsRes.right().value());
904                 }
905             }
906         } else {
907             Either<Resource, ResponseFormat> createdCsarArtifactsEither = handleVfCsarArtifacts(preparedResource, csarInfo, createdArtifacts,
908                 new ArtifactOperationInfo(false, false, operation), shouldLock, inTransaction);
909             log.trace("************* Finished to add artifacts from yaml {}", yamlFileName);
910             if (createdCsarArtifactsEither.isRight()) {
911                 return createdCsarArtifactsEither;
912             }
913             resource = createdCsarArtifactsEither.left().value();
914         }
915         return Either.left(resource);
916     }
917
918     protected Either<Resource, ResponseFormat> handleVfCsarArtifacts(Resource resource, CsarInfo csarInfo, List<ArtifactDefinition> createdArtifacts,
919                                                                      ArtifactOperationInfo artifactOperation, boolean shouldLock,
920                                                                      boolean inTransaction) {
921         if (csarInfo.getCsar() != null) {
922             createOrUpdateSingleNonMetaArtifactToComstants(resource, csarInfo, artifactOperation, shouldLock, inTransaction);
923             Either<Resource, ResponseFormat> eitherCreateResult = createOrUpdateNonMetaArtifacts(csarInfo, resource, createdArtifacts, shouldLock,
924                 inTransaction, artifactOperation);
925             if (eitherCreateResult.isRight()) {
926                 return Either.right(eitherCreateResult.right().value());
927             }
928             Either<Resource, StorageOperationStatus> eitherGerResource = toscaOperationFacade.getToscaElement(resource.getUniqueId());
929             if (eitherGerResource.isRight()) {
930                 ResponseFormat responseFormat = componentsUtils
931                     .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(eitherGerResource.right().value()), resource);
932                 return Either.right(responseFormat);
933             }
934             resource = eitherGerResource.left().value();
935             Either<ImmutablePair<String, String>, ResponseFormat> artifacsMetaCsarStatus = CsarValidationUtils
936                 .getArtifactsMeta(csarInfo.getCsar(), csarInfo.getCsarUUID(), componentsUtils);
937             if (artifacsMetaCsarStatus.isLeft()) {
938                 return getResourceResponseFormatEither(resource, csarInfo, createdArtifacts, artifactOperation, shouldLock, inTransaction,
939                     artifacsMetaCsarStatus);
940             } else {
941                 return csarArtifactsAndGroupsBusinessLogic.deleteVFModules(resource, csarInfo, shouldLock, inTransaction);
942             }
943         }
944         return Either.left(resource);
945     }
946
947     protected void createOrUpdateSingleNonMetaArtifactToComstants(Resource resource, CsarInfo csarInfo, ArtifactOperationInfo artifactOperation,
948                                                                   boolean shouldLock, boolean inTransaction) {
949         String vendorLicenseModelId = null;
950         String vfLicenseModelId = null;
951         if (artifactOperation.getArtifactOperationEnum() == ArtifactOperationEnum.UPDATE) {
952             Map<String, ArtifactDefinition> deploymentArtifactsMap = resource.getDeploymentArtifacts();
953             if (deploymentArtifactsMap != null && !deploymentArtifactsMap.isEmpty()) {
954                 for (Map.Entry<String, ArtifactDefinition> artifactEntry : deploymentArtifactsMap.entrySet()) {
955                     if (artifactEntry.getValue().getArtifactName().equalsIgnoreCase(Constants.VENDOR_LICENSE_MODEL)) {
956                         vendorLicenseModelId = artifactEntry.getValue().getUniqueId();
957                     }
958                     if (artifactEntry.getValue().getArtifactName().equalsIgnoreCase(Constants.VF_LICENSE_MODEL)) {
959                         vfLicenseModelId = artifactEntry.getValue().getUniqueId();
960                     }
961                 }
962             }
963         }
964         createOrUpdateSingleNonMetaArtifact(resource, csarInfo, CsarUtils.ARTIFACTS_PATH + Constants.VENDOR_LICENSE_MODEL,
965             Constants.VENDOR_LICENSE_MODEL, ArtifactTypeEnum.VENDOR_LICENSE.getType(), ArtifactGroupTypeEnum.DEPLOYMENT,
966             Constants.VENDOR_LICENSE_LABEL, Constants.VENDOR_LICENSE_DISPLAY_NAME, Constants.VENDOR_LICENSE_DESCRIPTION, vendorLicenseModelId,
967             artifactOperation, null, true, shouldLock, inTransaction);
968         createOrUpdateSingleNonMetaArtifact(resource, csarInfo, CsarUtils.ARTIFACTS_PATH + Constants.VF_LICENSE_MODEL, Constants.VF_LICENSE_MODEL,
969             ArtifactTypeEnum.VF_LICENSE.getType(), ArtifactGroupTypeEnum.DEPLOYMENT, Constants.VF_LICENSE_LABEL, Constants.VF_LICENSE_DISPLAY_NAME,
970             Constants.VF_LICENSE_DESCRIPTION, vfLicenseModelId, artifactOperation, null, true, shouldLock, inTransaction);
971     }
972
973     private Either<Resource, ResponseFormat> getResourceResponseFormatEither(Resource resource, CsarInfo csarInfo,
974                                                                              List<ArtifactDefinition> createdArtifacts,
975                                                                              ArtifactOperationInfo artifactOperation, boolean shouldLock,
976                                                                              boolean inTransaction,
977                                                                              Either<ImmutablePair<String, String>, ResponseFormat> artifacsMetaCsarStatus) {
978         try {
979             String artifactsFileName = artifacsMetaCsarStatus.left().value().getKey();
980             String artifactsContents = artifacsMetaCsarStatus.left().value().getValue();
981             Either<Resource, ResponseFormat> createArtifactsFromCsar;
982             if (ArtifactOperationEnum.isCreateOrLink(artifactOperation.getArtifactOperationEnum())) {
983                 createArtifactsFromCsar = csarArtifactsAndGroupsBusinessLogic
984                     .createResourceArtifactsFromCsar(csarInfo, resource, artifactsContents, artifactsFileName, createdArtifacts);
985             } else {
986                 Either<Component, ResponseFormat> result = csarArtifactsAndGroupsBusinessLogic
987                     .updateResourceArtifactsFromCsar(csarInfo, resource, artifactsContents, artifactsFileName, createdArtifacts, shouldLock,
988                         inTransaction);
989                 if ((result.left().value() instanceof Resource) && result.isLeft()) {
990                     Resource service1 = (Resource) result.left().value();
991                     createArtifactsFromCsar = Either.left(service1);
992                 } else {
993                     createArtifactsFromCsar = Either.right(result.right().value());
994                 }
995             }
996             if (createArtifactsFromCsar.isRight()) {
997                 log.debug("Couldn't create artifacts from artifacts.meta");
998                 return Either.right(createArtifactsFromCsar.right().value());
999             }
1000             return Either.left(createArtifactsFromCsar.left().value());
1001         } catch (Exception e) {
1002             log.debug("Exception occured in getResourceResponseFormatEither, message:{}", e.getMessage(), e);
1003             return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
1004         }
1005     }
1006
1007     private <T extends Component> Either<T, ResponseFormat> createOrUpdateNonMetaArtifactsComp(CsarInfo csarInfo, T component,
1008                                                                                                List<ArtifactDefinition> createdArtifacts,
1009                                                                                                boolean shouldLock, boolean inTransaction,
1010                                                                                                ArtifactOperationInfo artifactOperation) {
1011         Either<T, ResponseFormat> resStatus = null;
1012         Map<String, Set<List<String>>> collectedWarningMessages = new HashMap<>();
1013         try {
1014             Either<List<CsarUtils.NonMetaArtifactInfo>, String> artifactPathAndNameList = getValidArtifactNames(csarInfo, collectedWarningMessages);
1015             if (artifactPathAndNameList.isRight()) {
1016                 return Either.right(
1017                     getComponentsUtils().getResponseFormatByArtifactId(ActionStatus.ARTIFACT_NAME_INVALID, artifactPathAndNameList.right().value()));
1018             }
1019             EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<CsarUtils.NonMetaArtifactInfo>> vfCsarArtifactsToHandle = null;
1020             if (ArtifactsBusinessLogic.ArtifactOperationEnum.isCreateOrLink(artifactOperation.getArtifactOperationEnum())) {
1021                 vfCsarArtifactsToHandle = new EnumMap<>(ArtifactsBusinessLogic.ArtifactOperationEnum.class);
1022                 vfCsarArtifactsToHandle.put(artifactOperation.getArtifactOperationEnum(), artifactPathAndNameList.left().value());
1023             } else {
1024                 Either<EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<CsarUtils.NonMetaArtifactInfo>>, ResponseFormat> findVfCsarArtifactsToHandleRes = findVfCsarArtifactsToHandle(
1025                     component, artifactPathAndNameList.left().value(), csarInfo.getModifier());
1026                 if (findVfCsarArtifactsToHandleRes.isRight()) {
1027                     resStatus = Either.right(findVfCsarArtifactsToHandleRes.right().value());
1028                 }
1029                 if (resStatus == null) {
1030                     vfCsarArtifactsToHandle = findVfCsarArtifactsToHandleRes.left().value();
1031                 }
1032             }
1033             if (resStatus == null && vfCsarArtifactsToHandle != null) {
1034                 resStatus = processCsarArtifacts(csarInfo, component, createdArtifacts, shouldLock, inTransaction, resStatus,
1035                     vfCsarArtifactsToHandle);
1036             }
1037             if (resStatus == null) {
1038                 resStatus = Either.left(component);
1039             }
1040         } catch (Exception e) {
1041             resStatus = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
1042             log.debug("Exception occured in createNonMetaArtifacts, message:{}", e.getMessage(), e);
1043         } finally {
1044             CsarUtils.handleWarningMessages(collectedWarningMessages);
1045         }
1046         return resStatus;
1047     }
1048
1049     protected Either<Resource, ResponseFormat> createOrUpdateNonMetaArtifacts(CsarInfo csarInfo, Resource resource,
1050                                                                               List<ArtifactDefinition> createdArtifacts, boolean shouldLock,
1051                                                                               boolean inTransaction, ArtifactOperationInfo artifactOperation) {
1052         return createOrUpdateNonMetaArtifactsComp(csarInfo, resource, createdArtifacts, shouldLock, inTransaction, artifactOperation);
1053     }
1054
1055     protected <T extends Component> Either<T, ResponseFormat> processCsarArtifacts(CsarInfo csarInfo, Component comp,
1056                                                                                    List<ArtifactDefinition> createdArtifacts, boolean shouldLock,
1057                                                                                    boolean inTransaction, Either<T, ResponseFormat> resStatus,
1058                                                                                    EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<CsarUtils.NonMetaArtifactInfo>> vfCsarArtifactsToHandle) {
1059         for (Map.Entry<ArtifactsBusinessLogic.ArtifactOperationEnum, List<CsarUtils.NonMetaArtifactInfo>> currArtifactOperationPair : vfCsarArtifactsToHandle
1060             .entrySet()) {
1061             Optional<ResponseFormat> optionalCreateInDBError = currArtifactOperationPair.getValue().stream().map(
1062                 e -> createOrUpdateSingleNonMetaArtifact(comp, csarInfo, e.getPath(), e.getArtifactName(), e.getArtifactType(),
1063                     e.getArtifactGroupType(), e.getArtifactLabel(), e.getDisplayName(), CsarUtils.ARTIFACT_CREATED_FROM_CSAR, e.getArtifactUniqueId(),
1064                     new ArtifactOperationInfo(false, false, currArtifactOperationPair.getKey()), createdArtifacts, e.isFromCsar(), shouldLock,
1065                     inTransaction)).filter(Either::isRight).map(e -> e.right().value()).findAny();
1066             if (optionalCreateInDBError.isPresent()) {
1067                 resStatus = Either.right(optionalCreateInDBError.get());
1068                 break;
1069             }
1070         }
1071         return resStatus;
1072     }
1073
1074     protected Either<Boolean, ResponseFormat> createOrUpdateSingleNonMetaArtifact(Component component, CsarInfo csarInfo, String artifactPath,
1075                                                                                   String artifactFileName, String artifactType,
1076                                                                                   ArtifactGroupTypeEnum artifactGroupType, String artifactLabel,
1077                                                                                   String artifactDisplayName, String artifactDescription,
1078                                                                                   String artifactId, ArtifactOperationInfo operation,
1079                                                                                   List<ArtifactDefinition> createdArtifacts, boolean isFromCsar,
1080                                                                                   boolean shouldLock, boolean inTransaction) {
1081         byte[] artifactFileBytes = null;
1082         if (csarInfo.getCsar().containsKey(artifactPath)) {
1083             artifactFileBytes = csarInfo.getCsar().get(artifactPath);
1084         }
1085         Either<Boolean, ResponseFormat> result = Either.left(true);
1086         if (operation.getArtifactOperationEnum() == ArtifactsBusinessLogic.ArtifactOperationEnum.UPDATE
1087             || operation.getArtifactOperationEnum() == ArtifactsBusinessLogic.ArtifactOperationEnum.DELETE) {
1088             if (serviceImportParseLogic.isArtifactDeletionRequired(artifactId, artifactFileBytes, isFromCsar)) {
1089                 Either<ArtifactDefinition, ResponseFormat> handleDelete = artifactsBusinessLogic
1090                     .handleDelete(component.getUniqueId(), artifactId, csarInfo.getModifier(), component, shouldLock, inTransaction);
1091                 if (handleDelete.isRight()) {
1092                     result = Either.right(handleDelete.right().value());
1093                 }
1094                 return result;
1095             }
1096             if (org.apache.commons.lang.StringUtils.isEmpty(artifactId) && artifactFileBytes != null) {
1097                 operation = new ArtifactOperationInfo(false, false, ArtifactsBusinessLogic.ArtifactOperationEnum.CREATE);
1098             }
1099         }
1100         if (artifactFileBytes != null) {
1101             Map<String, Object> vendorLicenseModelJson = ArtifactUtils
1102                 .buildJsonForUpdateArtifact(artifactId, artifactFileName, artifactType, artifactGroupType, artifactLabel, artifactDisplayName,
1103                     artifactDescription, artifactFileBytes, null, isFromCsar);
1104             Either<Either<ArtifactDefinition, Operation>, ResponseFormat> eitherNonMetaArtifacts = csarArtifactsAndGroupsBusinessLogic
1105                 .createOrUpdateCsarArtifactFromJson(component, csarInfo.getModifier(), vendorLicenseModelJson, operation);
1106             serviceImportParseLogic.addNonMetaCreatedArtifactsToSupportRollback(operation, createdArtifacts, eitherNonMetaArtifacts);
1107             if (eitherNonMetaArtifacts.isRight()) {
1108                 BeEcompErrorManager.getInstance().logInternalFlowError("UploadLicenseArtifact",
1109                     "Failed to upload license artifact: " + artifactFileName + "With csar uuid: " + csarInfo.getCsarUUID(),
1110                     BeEcompErrorManager.ErrorSeverity.WARNING);
1111                 return Either.right(eitherNonMetaArtifacts.right().value());
1112             }
1113         }
1114         return result;
1115     }
1116
1117     private Either<List<ArtifactDefinition>, ResponseFormat> handleNodeTypeArtifacts(Resource nodeTypeResource,
1118                                                                                      Map<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle,
1119                                                                                      List<ArtifactDefinition> createdArtifacts, User user,
1120                                                                                      boolean inTransaction, boolean ignoreLifecycleState) {
1121         List<ArtifactDefinition> handleNodeTypeArtifactsRequestRes;
1122         Either<List<ArtifactDefinition>, ResponseFormat> handleNodeTypeArtifactsRes = null;
1123         Either<Resource, ResponseFormat> changeStateResponse;
1124         try {
1125             changeStateResponse = checkoutResource(nodeTypeResource, user, inTransaction);
1126             if (changeStateResponse.isRight()) {
1127                 return Either.right(changeStateResponse.right().value());
1128             }
1129             nodeTypeResource = changeStateResponse.left().value();
1130             List<ArtifactDefinition> handledNodeTypeArtifacts = new ArrayList<>();
1131             log.debug("************* Going to handle artifacts of node type resource {}. ", nodeTypeResource.getName());
1132             for (Map.Entry<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>> curOperationEntry : nodeTypeArtifactsToHandle
1133                 .entrySet()) {
1134                 ArtifactsBusinessLogic.ArtifactOperationEnum curOperation = curOperationEntry.getKey();
1135                 List<ArtifactDefinition> curArtifactsToHandle = curOperationEntry.getValue();
1136                 if (curArtifactsToHandle != null && !curArtifactsToHandle.isEmpty()) {
1137                     log.debug("************* Going to {} artifact to vfc {}", curOperation.name(), nodeTypeResource.getName());
1138                     handleNodeTypeArtifactsRequestRes = artifactsBusinessLogic
1139                         .handleArtifactsRequestForInnerVfcComponent(curArtifactsToHandle, nodeTypeResource, user, createdArtifacts,
1140                             new ArtifactOperationInfo(false, ignoreLifecycleState, curOperation), false, inTransaction);
1141                     if (ArtifactsBusinessLogic.ArtifactOperationEnum.isCreateOrLink(curOperation)) {
1142                         createdArtifacts.addAll(handleNodeTypeArtifactsRequestRes);
1143                     }
1144                     handledNodeTypeArtifacts.addAll(handleNodeTypeArtifactsRequestRes);
1145                 }
1146             }
1147             handleNodeTypeArtifactsRes = Either.left(handledNodeTypeArtifacts);
1148         } catch (Exception e) {
1149             ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
1150             handleNodeTypeArtifactsRes = Either.right(responseFormat);
1151             log.debug("Exception occured when handleVfcArtifacts, error is:{}", e.getMessage(), e);
1152         }
1153         return handleNodeTypeArtifactsRes;
1154     }
1155
1156     private Either<Resource, ResponseFormat> checkoutResource(Resource resource, User user, boolean inTransaction) {
1157         Either<Resource, ResponseFormat> checkoutResourceRes;
1158         try {
1159             if (!resource.getComponentMetadataDefinition().getMetadataDataDefinition().getState()
1160                 .equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
1161                 Either<? extends Component, ResponseFormat> checkoutRes = lifecycleBusinessLogic
1162                     .changeComponentState(resource.getComponentType(), resource.getUniqueId(), user, LifeCycleTransitionEnum.CHECKOUT,
1163                         new LifecycleChangeInfoWithAction(CERTIFICATION_ON_IMPORT,
1164                             LifecycleChangeInfoWithAction.LifecycleChanceActionEnum.CREATE_FROM_CSAR), inTransaction, true);
1165                 if (checkoutRes.isRight()) {
1166                     checkoutResourceRes = Either.right(checkoutRes.right().value());
1167                 } else {
1168                     checkoutResourceRes = Either.left((Resource) checkoutRes.left().value());
1169                 }
1170             } else {
1171                 checkoutResourceRes = Either.left(resource);
1172             }
1173         } catch (Exception e) {
1174             ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
1175             checkoutResourceRes = Either.right(responseFormat);
1176             log.debug("Exception occured when checkoutResource {} , error is:{}", resource.getName(), e.getMessage(), e);
1177         }
1178         return checkoutResourceRes;
1179     }
1180
1181     protected Either<Service, ResponseFormat> createOrUpdateArtifacts(ArtifactOperationEnum operation, List<ArtifactDefinition> createdArtifacts,
1182                                                                       String yamlFileName, CsarInfo csarInfo, Service preparedService,
1183                                                                       NodeTypeInfoToUpdateArtifacts nodeTypeInfoToUpdateArtifacts,
1184                                                                       boolean inTransaction, boolean shouldLock) {
1185         Either<Service, ResponseFormat> createdCsarArtifactsEither = handleVfCsarArtifacts(preparedService, csarInfo, createdArtifacts,
1186             new ArtifactOperationInfo(false, false, operation), shouldLock, inTransaction);
1187         log.trace("************* Finished to add artifacts from yaml {}", yamlFileName);
1188         if (createdCsarArtifactsEither.isRight()) {
1189             return createdCsarArtifactsEither;
1190         }
1191         return Either.left(createdCsarArtifactsEither.left().value());
1192     }
1193
1194     protected Either<Service, ResponseFormat> handleVfCsarArtifacts(Service service, CsarInfo csarInfo, List<ArtifactDefinition> createdArtifacts,
1195                                                                     ArtifactOperationInfo artifactOperation, boolean shouldLock,
1196                                                                     boolean inTransaction) {
1197         if (csarInfo.getCsar() != null) {
1198             String vendorLicenseModelId = null;
1199             String vfLicenseModelId = null;
1200             if (artifactOperation.getArtifactOperationEnum() == ArtifactsBusinessLogic.ArtifactOperationEnum.UPDATE) {
1201                 Map<String, ArtifactDefinition> deploymentArtifactsMap = service.getDeploymentArtifacts();
1202                 if (deploymentArtifactsMap != null && !deploymentArtifactsMap.isEmpty()) {
1203                     for (Map.Entry<String, ArtifactDefinition> artifactEntry : deploymentArtifactsMap.entrySet()) {
1204                         if (artifactEntry.getValue().getArtifactName().equalsIgnoreCase(Constants.VENDOR_LICENSE_MODEL)) {
1205                             vendorLicenseModelId = artifactEntry.getValue().getUniqueId();
1206                         }
1207                         if (artifactEntry.getValue().getArtifactName().equalsIgnoreCase(Constants.VF_LICENSE_MODEL)) {
1208                             vfLicenseModelId = artifactEntry.getValue().getUniqueId();
1209                         }
1210                     }
1211                 }
1212             }
1213             createOrUpdateSingleNonMetaArtifact(service, csarInfo, CsarUtils.ARTIFACTS_PATH + Constants.VENDOR_LICENSE_MODEL,
1214                 Constants.VENDOR_LICENSE_MODEL, ArtifactTypeEnum.VENDOR_LICENSE.getType(), ArtifactGroupTypeEnum.DEPLOYMENT,
1215                 Constants.VENDOR_LICENSE_LABEL, Constants.VENDOR_LICENSE_DISPLAY_NAME, Constants.VENDOR_LICENSE_DESCRIPTION, vendorLicenseModelId,
1216                 artifactOperation, null, true, shouldLock, inTransaction);
1217             createOrUpdateSingleNonMetaArtifact(service, csarInfo, CsarUtils.ARTIFACTS_PATH + Constants.VF_LICENSE_MODEL, Constants.VF_LICENSE_MODEL,
1218                 ArtifactTypeEnum.VF_LICENSE.getType(), ArtifactGroupTypeEnum.DEPLOYMENT, Constants.VF_LICENSE_LABEL,
1219                 Constants.VF_LICENSE_DISPLAY_NAME, Constants.VF_LICENSE_DESCRIPTION, vfLicenseModelId, artifactOperation, null, true, shouldLock,
1220                 inTransaction);
1221             Either<Service, ResponseFormat> eitherCreateResult = createOrUpdateNonMetaArtifacts(csarInfo, service, createdArtifacts, shouldLock,
1222                 inTransaction, artifactOperation);
1223             if (eitherCreateResult.isRight()) {
1224                 return Either.right(eitherCreateResult.right().value());
1225             }
1226             Either<Service, StorageOperationStatus> eitherGerResource = toscaOperationFacade.getToscaElement(service.getUniqueId());
1227             if (eitherGerResource.isRight()) {
1228                 ResponseFormat responseFormat = componentsUtils
1229                     .getResponseFormatByComponent(componentsUtils.convertFromStorageResponse(eitherGerResource.right().value()), service,
1230                         ComponentTypeEnum.SERVICE);
1231                 return Either.right(responseFormat);
1232             }
1233             service = eitherGerResource.left().value();
1234             Either<ImmutablePair<String, String>, ResponseFormat> artifacsMetaCsarStatus = CsarValidationUtils
1235                 .getArtifactsMeta(csarInfo.getCsar(), csarInfo.getCsarUUID(), componentsUtils);
1236             if (artifacsMetaCsarStatus.isLeft()) {
1237                 String artifactsFileName = artifacsMetaCsarStatus.left().value().getKey();
1238                 String artifactsContents = artifacsMetaCsarStatus.left().value().getValue();
1239                 Either<Service, ResponseFormat> createArtifactsFromCsar;
1240                 if (ArtifactsBusinessLogic.ArtifactOperationEnum.isCreateOrLink(artifactOperation.getArtifactOperationEnum())) {
1241                     createArtifactsFromCsar = csarArtifactsAndGroupsBusinessLogic
1242                         .createResourceArtifactsFromCsar(csarInfo, service, artifactsContents, artifactsFileName, createdArtifacts);
1243                 } else {
1244                     Either<Component, ResponseFormat> result = csarArtifactsAndGroupsBusinessLogic
1245                         .updateResourceArtifactsFromCsar(csarInfo, service, artifactsContents, artifactsFileName, createdArtifacts, shouldLock,
1246                             inTransaction);
1247                     if ((result.left().value() instanceof Service) && result.isLeft()) {
1248                         Service service1 = (Service) result.left().value();
1249                         createArtifactsFromCsar = Either.left(service1);
1250                     } else {
1251                         createArtifactsFromCsar = Either.right(result.right().value());
1252                     }
1253                 }
1254                 if (createArtifactsFromCsar.isRight()) {
1255                     log.debug("Couldn't create artifacts from artifacts.meta");
1256                     return Either.right(createArtifactsFromCsar.right().value());
1257                 }
1258                 return Either.left(createArtifactsFromCsar.left().value());
1259             } else {
1260                 return csarArtifactsAndGroupsBusinessLogic.deleteVFModules(service, csarInfo, shouldLock, inTransaction);
1261             }
1262         }
1263         return Either.left(service);
1264     }
1265
1266     protected Either<Service, ResponseFormat> createOrUpdateNonMetaArtifacts(CsarInfo csarInfo, Service resource,
1267                                                                              List<ArtifactDefinition> createdArtifacts, boolean shouldLock,
1268                                                                              boolean inTransaction, ArtifactOperationInfo artifactOperation) {
1269         return createOrUpdateNonMetaArtifactsComp(csarInfo, resource, createdArtifacts, shouldLock, inTransaction, artifactOperation);
1270     }
1271
1272     protected Either<EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<CsarUtils.NonMetaArtifactInfo>>, ResponseFormat> findVfCsarArtifactsToHandle(
1273         Component component, List<CsarUtils.NonMetaArtifactInfo> artifactPathAndNameList, User user) {
1274         List<ArtifactDefinition> existingArtifacts = new ArrayList<>();
1275         if (component.getDeploymentArtifacts() != null && !component.getDeploymentArtifacts().isEmpty()) {
1276             existingArtifacts.addAll(component.getDeploymentArtifacts().values());
1277         }
1278         if (component.getArtifacts() != null && !component.getArtifacts().isEmpty()) {
1279             existingArtifacts.addAll(component.getArtifacts().values());
1280         }
1281         existingArtifacts = existingArtifacts.stream().filter(this::isNonMetaArtifact).collect(toList());
1282         List<String> artifactsToIgnore = new ArrayList<>();
1283         if (component.getGroups() != null) {
1284             component.getGroups().forEach(g -> {
1285                 if (g.getArtifacts() != null && !g.getArtifacts().isEmpty()) {
1286                     artifactsToIgnore.addAll(g.getArtifacts());
1287                 }
1288             });
1289         }
1290         existingArtifacts = existingArtifacts.stream().filter(a -> !artifactsToIgnore.contains(a.getUniqueId())).collect(toList());
1291         return organizeVfCsarArtifactsByArtifactOperation(artifactPathAndNameList, existingArtifacts, component, user);
1292     }
1293
1294     private boolean isNonMetaArtifact(ArtifactDefinition artifact) {
1295         boolean result = true;
1296         if (artifact.getMandatory() || artifact.getArtifactName() == null || !isValidArtifactType(artifact)) {
1297             result = false;
1298         }
1299         return result;
1300     }
1301
1302     private boolean isValidArtifactType(ArtifactDefinition artifact) {
1303         final String artifactType = artifact.getArtifactType();
1304         return artifactType != null
1305             && !ArtifactTypeEnum.VENDOR_LICENSE.getType().equals(ArtifactTypeEnum.findType(artifactType))
1306             && !ArtifactTypeEnum.VF_LICENSE.getType().equals(ArtifactTypeEnum.findType(artifactType));
1307     }
1308
1309     protected Either<EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<CsarUtils.NonMetaArtifactInfo>>, ResponseFormat> organizeVfCsarArtifactsByArtifactOperation(
1310         List<CsarUtils.NonMetaArtifactInfo> artifactPathAndNameList, List<ArtifactDefinition> existingArtifactsToHandle, Component component,
1311         User user) {
1312         EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<CsarUtils.NonMetaArtifactInfo>> nodeTypeArtifactsToHandle = new EnumMap<>(
1313             ArtifactsBusinessLogic.ArtifactOperationEnum.class);
1314         Wrapper<ResponseFormat> responseWrapper = new Wrapper<>();
1315         Either<EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<CsarUtils.NonMetaArtifactInfo>>, ResponseFormat> nodeTypeArtifactsToHandleRes = Either
1316             .left(nodeTypeArtifactsToHandle);
1317         try {
1318             List<CsarUtils.NonMetaArtifactInfo> artifactsToUpload = new ArrayList<>(artifactPathAndNameList);
1319             List<CsarUtils.NonMetaArtifactInfo> artifactsToUpdate = new ArrayList<>();
1320             List<CsarUtils.NonMetaArtifactInfo> artifactsToDelete = new ArrayList<>();
1321             for (CsarUtils.NonMetaArtifactInfo currNewArtifact : artifactPathAndNameList) {
1322                 ArtifactDefinition foundArtifact;
1323                 if (!existingArtifactsToHandle.isEmpty()) {
1324                     foundArtifact = existingArtifactsToHandle.stream().filter(a -> a.getArtifactName().equals(currNewArtifact.getArtifactName()))
1325                         .findFirst().orElse(null);
1326                     if (foundArtifact != null) {
1327                         if (ArtifactTypeEnum.findType(foundArtifact.getArtifactType()).equals(currNewArtifact.getArtifactType())) {
1328                             if (!foundArtifact.getArtifactChecksum().equals(currNewArtifact.getArtifactChecksum())) {
1329                                 currNewArtifact.setArtifactUniqueId(foundArtifact.getUniqueId());
1330                                 artifactsToUpdate.add(currNewArtifact);
1331                             }
1332                             existingArtifactsToHandle.remove(foundArtifact);
1333                             artifactsToUpload.remove(currNewArtifact);
1334                         } else {
1335                             log.debug("Can't upload two artifact with the same name {}.", currNewArtifact.getArtifactName());
1336                             ResponseFormat responseFormat = ResponseFormatManager.getInstance()
1337                                 .getResponseFormat(ActionStatus.ARTIFACT_ALREADY_EXIST_IN_DIFFERENT_TYPE_IN_CSAR, currNewArtifact.getArtifactName(),
1338                                     currNewArtifact.getArtifactType(), foundArtifact.getArtifactType());
1339                             AuditingActionEnum auditingAction = artifactsBusinessLogic.detectAuditingType(
1340                                 new ArtifactOperationInfo(false, false, ArtifactsBusinessLogic.ArtifactOperationEnum.CREATE),
1341                                 foundArtifact.getArtifactChecksum());
1342                             artifactsBusinessLogic.handleAuditing(auditingAction, component, component.getUniqueId(), user, null, null,
1343                                 foundArtifact.getUniqueId(), responseFormat, component.getComponentType(), null);
1344                             responseWrapper.setInnerElement(responseFormat);
1345                             break;
1346                         }
1347                     }
1348                 }
1349             }
1350             if (responseWrapper.isEmpty()) {
1351                 for (ArtifactDefinition currArtifact : existingArtifactsToHandle) {
1352                     if (currArtifact.getIsFromCsar()) {
1353                         artifactsToDelete.add(new CsarUtils.NonMetaArtifactInfo(currArtifact.getArtifactName(), null,
1354                             ArtifactTypeEnum.findType(currArtifact.getArtifactType()), currArtifact.getArtifactGroupType(), null,
1355                             currArtifact.getUniqueId(), currArtifact.getIsFromCsar()));
1356                     } else {
1357                         artifactsToUpdate.add(new CsarUtils.NonMetaArtifactInfo(currArtifact.getArtifactName(), null,
1358                             ArtifactTypeEnum.findType(currArtifact.getArtifactType()), currArtifact.getArtifactGroupType(), null,
1359                             currArtifact.getUniqueId(), currArtifact.getIsFromCsar()));
1360                     }
1361                 }
1362             }
1363             if (responseWrapper.isEmpty()) {
1364                 if (!artifactsToUpload.isEmpty()) {
1365                     nodeTypeArtifactsToHandle.put(ArtifactsBusinessLogic.ArtifactOperationEnum.CREATE, artifactsToUpload);
1366                 }
1367                 if (!artifactsToUpdate.isEmpty()) {
1368                     nodeTypeArtifactsToHandle.put(ArtifactsBusinessLogic.ArtifactOperationEnum.UPDATE, artifactsToUpdate);
1369                 }
1370                 if (!artifactsToDelete.isEmpty()) {
1371                     nodeTypeArtifactsToHandle.put(ArtifactsBusinessLogic.ArtifactOperationEnum.DELETE, artifactsToDelete);
1372                 }
1373             }
1374             if (!responseWrapper.isEmpty()) {
1375                 nodeTypeArtifactsToHandleRes = Either.right(responseWrapper.getInnerElement());
1376             }
1377         } catch (Exception e) {
1378             ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
1379             responseWrapper.setInnerElement(responseFormat);
1380             log.debug("Exception occured when findNodeTypeArtifactsToHandle, error is:{}", e.getMessage(), e);
1381             nodeTypeArtifactsToHandleRes = Either.right(responseWrapper.getInnerElement());
1382         }
1383         return nodeTypeArtifactsToHandleRes;
1384     }
1385
1386     protected Either<List<CsarUtils.NonMetaArtifactInfo>, String> getValidArtifactNames(CsarInfo csarInfo,
1387                                                                                         Map<String, Set<List<String>>> collectedWarningMessages) {
1388         List<CsarUtils.NonMetaArtifactInfo> artifactPathAndNameList = csarInfo.getCsar().entrySet().stream()
1389             .filter(e -> Pattern.compile(VF_NODE_TYPE_ARTIFACTS_PATH_PATTERN).matcher(e.getKey()).matches())
1390             .map(e -> CsarUtils.validateNonMetaArtifact(e.getKey(), e.getValue(), collectedWarningMessages)).filter(Either::isLeft)
1391             .map(e -> e.left().value()).collect(toList());
1392         Pattern englishNumbersAndUnderScoresOnly = Pattern.compile(CsarUtils.VALID_ENGLISH_ARTIFACT_NAME);
1393         for (CsarUtils.NonMetaArtifactInfo nonMetaArtifactInfo : artifactPathAndNameList) {
1394             if (!englishNumbersAndUnderScoresOnly.matcher(nonMetaArtifactInfo.getDisplayName()).matches()) {
1395                 return Either.right(nonMetaArtifactInfo.getArtifactName());
1396             }
1397         }
1398         return Either.left(artifactPathAndNameList);
1399     }
1400
1401     protected Either<Service, ResponseFormat> createGroupsOnResource(Service service, Map<String, GroupDefinition> groups) {
1402         if (groups != null && !groups.isEmpty()) {
1403             List<GroupDefinition> groupsAsList = updateGroupsMembersUsingResource(groups, service);
1404             serviceImportParseLogic.handleGroupsProperties(service, groups);
1405             serviceImportParseLogic.fillGroupsFinalFields(groupsAsList);
1406             Either<List<GroupDefinition>, ResponseFormat> createGroups = groupBusinessLogic.createGroups(service, groupsAsList, true);
1407             if (createGroups.isRight()) {
1408                 return Either.right(createGroups.right().value());
1409             }
1410         } else {
1411             return Either.left(service);
1412         }
1413         return getServiceResponseFormatEither(service);
1414     }
1415
1416     private Either<Service, ResponseFormat> createPoliciesOnResource(final Service service,
1417                                                                      final Map<String, PolicyDefinition> policies) {
1418         if (MapUtils.isEmpty(policies)) {
1419             return Either.left(service);
1420         }
1421         Map<String, List<ComponentInstanceAttribute>> componentInstancesAttributes = service.getComponentInstancesAttributes();
1422         final Map<String, List<AttributeDefinition>> instanceAttributeMap = new HashMap<>();
1423         if (MapUtils.isNotEmpty(componentInstancesAttributes)) {
1424             instanceAttributeMap.putAll(componentInstancesAttributes
1425                 .entrySet().stream()
1426                 .collect(toMap(Entry::getKey, entry -> entry.getValue().stream().map(AttributeDefinition.class::cast).collect(toList()))));
1427         }
1428         policies.values().stream()
1429             .map(PolicyDataDefinition::getProperties)
1430             .flatMap(Collection::stream)
1431             .filter(PropertyDataDefinition::isToscaFunction)
1432             .forEach(policyDefinition -> toscaFunctionService
1433                 .updateFunctionWithDataFromSelfComponent(policyDefinition.getToscaFunction(), service, service.getComponentInstancesProperties(),
1434                     instanceAttributeMap)
1435             );
1436         policyBusinessLogic.createPolicies(service, policies);
1437         return getServiceResponseFormatEither(service);
1438     }
1439
1440     private Either<Service, ResponseFormat> getServiceResponseFormatEither(Service service) {
1441         Either<Service, StorageOperationStatus> updatedResource = toscaOperationFacade.getToscaElement(service.getUniqueId());
1442         if (updatedResource.isRight()) {
1443             ResponseFormat responseFormat = componentsUtils
1444                 .getResponseFormatByComponent(componentsUtils.convertFromStorageResponse(updatedResource.right().value()), service,
1445                     ComponentTypeEnum.SERVICE);
1446             return Either.right(responseFormat);
1447         }
1448         return Either.left(updatedResource.left().value());
1449     }
1450
1451     protected List<GroupDefinition> updateGroupsMembersUsingResource(Map<String, GroupDefinition> groups, Service component) {
1452         List<GroupDefinition> result = new ArrayList<>();
1453         List<ComponentInstance> componentInstances = component.getComponentInstances();
1454         if (groups != null) {
1455             for (Map.Entry<String, GroupDefinition> entry : groups.entrySet()) {
1456                 String groupName = entry.getKey();
1457                 GroupDefinition groupDefinition = entry.getValue();
1458                 GroupDefinition updatedGroupDefinition = new GroupDefinition(groupDefinition);
1459                 updatedGroupDefinition.setMembers(null);
1460                 Map<String, String> members = groupDefinition.getMembers();
1461                 if (members != null) {
1462                     serviceImportParseLogic.updateGroupMembers(groups, updatedGroupDefinition, component, componentInstances, groupName, members);
1463                 }
1464                 result.add(updatedGroupDefinition);
1465             }
1466         }
1467         return result;
1468     }
1469
1470     protected Resource createRIAndRelationsFromYaml(String yamlName, Resource resource,
1471                                                     Map<String, UploadComponentInstanceInfo> uploadComponentInstanceInfoMap,
1472                                                     String topologyTemplateYaml, List<ArtifactDefinition> nodeTypesNewCreatedArtifacts,
1473                                                     Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo,
1474                                                     Map<String, EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToCreate,
1475                                                     String nodeName) {
1476         try {
1477             log.debug("************* Going to create all nodes {}", yamlName);
1478             handleNodeTypes(yamlName, resource, topologyTemplateYaml, false, nodeTypesArtifactsToCreate, nodeTypesNewCreatedArtifacts, nodeTypesInfo,
1479                 csarInfo, nodeName);
1480             log.debug("************* Going to create all resource instances {}", yamlName);
1481             resource = createResourceInstances(yamlName, resource, uploadComponentInstanceInfoMap, csarInfo.getCreatedNodes());
1482             log.debug("************* Finished to create all resource instances {}", yamlName);
1483             resource = createResourceInstancesRelations(csarInfo.getModifier(), yamlName, resource, uploadComponentInstanceInfoMap);
1484             log.debug("************* Going to create positions {}", yamlName);
1485             compositionBusinessLogic.setPositionsForComponentInstances(resource, csarInfo.getModifier().getUserId());
1486             log.debug("************* Finished to set positions {}", yamlName);
1487             return resource;
1488         } catch (Exception e) {
1489             throw new ComponentException(ActionStatus.GENERAL_ERROR);
1490         }
1491     }
1492
1493     protected Resource createResourceInstancesRelations(User user, String yamlName, Resource resource,
1494                                                         Map<String, UploadComponentInstanceInfo> uploadResInstancesMap) {
1495         log.debug("#createResourceInstancesRelations - Going to create relations ");
1496         List<ComponentInstance> componentInstancesList = resource.getComponentInstances();
1497         if (((MapUtils.isEmpty(uploadResInstancesMap) || CollectionUtils.isEmpty(componentInstancesList)) &&
1498             resource.getResourceType() != ResourceTypeEnum.PNF)) { // PNF can have no resource instances
1499             log.debug("#createResourceInstancesRelations - No instances found in the resource {} is empty, yaml template file name {}, ",
1500                 resource.getUniqueId(), yamlName);
1501             BeEcompErrorManager.getInstance()
1502                 .logInternalDataError("createResourceInstancesRelations", "No instances found in a resource or nn yaml template. ",
1503                     BeEcompErrorManager.ErrorSeverity.ERROR);
1504             throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName));
1505         }
1506         Map<String, List<ComponentInstanceProperty>> instProperties = new HashMap<>();
1507         Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilities = new HashMap<>();
1508         Map<ComponentInstance, Map<String, List<RequirementDefinition>>> instRequirements = new HashMap<>();
1509         Map<String, Map<String, ArtifactDefinition>> instDeploymentArtifacts = new HashMap<>();
1510         Map<String, Map<String, ArtifactDefinition>> instArtifacts = new HashMap<>();
1511         Map<String, List<AttributeDefinition>> instAttributes = new HashMap<>();
1512         Map<String, Resource> originCompMap = new HashMap<>();
1513         List<RequirementCapabilityRelDef> relations = new ArrayList<>();
1514         Map<String, List<ComponentInstanceInput>> instInputs = new HashMap<>();
1515         Map<String, UploadNodeFilterInfo> instNodeFilter = new HashMap<>();
1516         Map<String, Map<String, InterfaceDefinition>> instInterfaces = new HashMap<>();
1517         log.debug("enter ServiceImportBusinessLogic createResourceInstancesRelations#createResourceInstancesRelations - Before get all datatypes. ");
1518         final ApplicationDataTypeCache applicationDataTypeCache = serviceBusinessLogic.applicationDataTypeCache;
1519         if (applicationDataTypeCache != null) {
1520             Resource finalResource = resource;
1521             uploadResInstancesMap.values().forEach(
1522                 i -> processComponentInstance(yamlName, finalResource, componentInstancesList,
1523                     componentsUtils.getAllDataTypes(applicationDataTypeCache, finalResource.getModel()), instProperties, instCapabilities,
1524                     instRequirements, instDeploymentArtifacts, instArtifacts, instAttributes, originCompMap, instInputs, instNodeFilter,
1525                     instInterfaces, i));
1526         }
1527         serviceImportParseLogic.associateComponentInstancePropertiesToComponent(yamlName, resource, instProperties);
1528         serviceImportParseLogic.associateComponentInstanceInputsToComponent(yamlName, resource, instInputs);
1529         serviceImportParseLogic.associateDeploymentArtifactsToInstances(user, yamlName, resource, instDeploymentArtifacts);
1530         serviceImportParseLogic.associateArtifactsToInstances(yamlName, resource, instArtifacts);
1531         serviceImportParseLogic.associateOrAddCalculatedCapReq(yamlName, resource, instCapabilities, instRequirements);
1532         serviceImportParseLogic.associateInstAttributeToComponentToInstances(yamlName, resource, instAttributes);
1533         resource = serviceImportParseLogic.getResourceAfterCreateRelations(resource);
1534         serviceImportParseLogic.addRelationsToRI(yamlName, resource, uploadResInstancesMap, componentInstancesList, relations);
1535         serviceImportParseLogic.associateResourceInstances(yamlName, resource, relations);
1536         handleSubstitutionMappings(resource, uploadResInstancesMap);
1537         log.debug("************* in create relations, getResource start");
1538         Either<Resource, StorageOperationStatus> eitherGetResource = toscaOperationFacade.getToscaElement(resource.getUniqueId());
1539         log.debug("************* in create relations, getResource end");
1540         if (eitherGetResource.isRight()) {
1541             throw new ComponentException(
1542                 componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(eitherGetResource.right().value()), resource));
1543         }
1544         return eitherGetResource.left().value();
1545     }
1546
1547     protected void processProperty(Resource resource, Map<String, DataTypeDefinition> allDataTypes,
1548                                    Map<String, InputDefinition> currPropertiesMap, List<ComponentInstanceInput> instPropList,
1549                                    List<UploadPropInfo> propertyList) {
1550         UploadPropInfo propertyInfo = propertyList.get(0);
1551         String propName = propertyInfo.getName();
1552         if (!currPropertiesMap.containsKey(propName)) {
1553             throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND, propName));
1554         }
1555         processProperty(allDataTypes, currPropertiesMap, instPropList, propertyInfo, propName, resource.getInputs());
1556     }
1557
1558     private void processProperty(Map<String, DataTypeDefinition> allDataTypes, Map<String, InputDefinition> currPropertiesMap,
1559                                  List<ComponentInstanceInput> instPropList, UploadPropInfo propertyInfo, String propName,
1560                                  List<InputDefinition> inputs2) {
1561         InputDefinition curPropertyDef = currPropertiesMap.get(propName);
1562         ComponentInstanceInput property = null;
1563         String value = null;
1564         List<GetInputValueDataDefinition> getInputs = null;
1565         boolean isValidate = true;
1566         if (propertyInfo.getValue() != null) {
1567             getInputs = propertyInfo.getGet_input();
1568             isValidate = getInputs == null || getInputs.isEmpty();
1569             if (isValidate) {
1570                 value = getPropertyJsonStringValue(propertyInfo.getValue(), curPropertyDef.getType());
1571             } else {
1572                 value = getPropertyJsonStringValue(propertyInfo.getValue(), TypeUtils.ToscaTagNamesEnum.GET_INPUT.getElementName());
1573             }
1574         }
1575         property = new ComponentInstanceInput(curPropertyDef, value, null);
1576         String validPropertyVAlue = serviceBusinessLogic.validatePropValueBeforeCreate(property, value, isValidate, allDataTypes);
1577         property.setValue(validPropertyVAlue);
1578         if (isNotEmpty(getInputs)) {
1579             List<GetInputValueDataDefinition> getInputValues = new ArrayList<>();
1580             for (GetInputValueDataDefinition getInput : getInputs) {
1581                 List<InputDefinition> inputs = inputs2;
1582                 if (CollectionUtils.isEmpty(inputs)) {
1583                     throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
1584                 }
1585                 Optional<InputDefinition> optional = inputs.stream().filter(p -> p.getName().equals(getInput.getInputName())).findAny();
1586                 if (!optional.isPresent()) {
1587                     throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
1588                 }
1589                 InputDefinition input = optional.get();
1590                 getInput.setInputId(input.getUniqueId());
1591                 getInputValues.add(getInput);
1592                 GetInputValueDataDefinition getInputIndex = getInput.getGetInputIndex();
1593                 processGetInput(getInputValues, inputs, getInputIndex);
1594             }
1595             property.setGetInputValues(getInputValues);
1596         }
1597         instPropList.add(property);
1598         currPropertiesMap.remove(property.getName());
1599     }
1600
1601     protected void handleSubstitutionMappings(Resource resource, Map<String, UploadComponentInstanceInfo> uploadResInstancesMap) {
1602         if (resource.getResourceType() == ResourceTypeEnum.VF) {
1603             Either<Resource, StorageOperationStatus> getResourceRes = toscaOperationFacade.getToscaFullElement(resource.getUniqueId());
1604             if (getResourceRes.isRight()) {
1605                 ResponseFormat responseFormat = componentsUtils
1606                     .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(getResourceRes.right().value()), resource);
1607                 throw new ComponentException(responseFormat);
1608             }
1609             getResourceRes = updateCalculatedCapReqWithSubstitutionMappings(getResourceRes.left().value(), uploadResInstancesMap);
1610             if (getResourceRes.isRight()) {
1611                 ResponseFormat responseFormat = componentsUtils
1612                     .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(getResourceRes.right().value()), resource);
1613                 throw new ComponentException(responseFormat);
1614             }
1615         }
1616     }
1617
1618     protected Resource createResourceInstances(String yamlName, Resource resource, Map<String, UploadComponentInstanceInfo> uploadResInstancesMap,
1619                                                Map<String, Resource> nodeNamespaceMap) {
1620         Either<Resource, ResponseFormat> eitherResource = null;
1621         log.debug("createResourceInstances is {} - going to create resource instanse from CSAR", yamlName);
1622         if (MapUtils.isEmpty(uploadResInstancesMap) && resource.getResourceType() != ResourceTypeEnum.PNF) { // PNF can have no resource instances
1623             ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE);
1624             throw new ComponentException(responseFormat);
1625         }
1626         Map<String, Resource> existingNodeTypeMap = new HashMap<>();
1627         if (MapUtils.isNotEmpty(nodeNamespaceMap)) {
1628             nodeNamespaceMap.forEach((k, v) -> existingNodeTypeMap.put(v.getToscaResourceName(), v));
1629         }
1630         Map<ComponentInstance, Resource> resourcesInstancesMap = new HashMap<>();
1631         uploadResInstancesMap.values()
1632             .forEach(i -> createAndAddResourceInstance(i, yamlName, resource, nodeNamespaceMap, existingNodeTypeMap, resourcesInstancesMap));
1633         if (MapUtils.isNotEmpty(resourcesInstancesMap)) {
1634             try {
1635                 toscaOperationFacade.associateComponentInstancesToComponent(resource, resourcesInstancesMap, false, false);
1636             } catch (StorageException exp) {
1637                 if (exp.getStorageOperationStatus() != null && exp.getStorageOperationStatus() != StorageOperationStatus.OK) {
1638                     log.debug("Failed to add component instances to container component {}", resource.getName());
1639                     ResponseFormat responseFormat = componentsUtils
1640                         .getResponseFormat(componentsUtils.convertFromStorageResponse(exp.getStorageOperationStatus()));
1641                     eitherResource = Either.right(responseFormat);
1642                     throw new ByResponseFormatComponentException(eitherResource.right().value());
1643                 }
1644             }
1645         }
1646         log.debug("*************Going to get resource {}", resource.getUniqueId());
1647         Either<Resource, StorageOperationStatus> eitherGetResource = toscaOperationFacade
1648             .getToscaElement(resource.getUniqueId(), serviceImportParseLogic.getComponentWithInstancesFilter());
1649         log.debug("*************finished to get resource {}", resource.getUniqueId());
1650         if (eitherGetResource.isRight()) {
1651             ResponseFormat responseFormat = componentsUtils
1652                 .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(eitherGetResource.right().value()), resource);
1653             throw new ComponentException(responseFormat);
1654         }
1655         if (CollectionUtils.isEmpty(eitherGetResource.left().value().getComponentInstances()) &&
1656             resource.getResourceType() != ResourceTypeEnum.PNF) { // PNF can have no resource instances
1657             log.debug("Error when create resource instance from csar. ComponentInstances list empty");
1658             BeEcompErrorManager.getInstance().logBeDaoSystemError("Error when create resource instance from csar. ComponentInstances list empty");
1659             throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE));
1660         }
1661         return eitherGetResource.left().value();
1662     }
1663
1664     protected void handleNodeTypes(String yamlName, Resource resource, String topologyTemplateYaml, boolean needLock,
1665                                    Map<String, EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle,
1666                                    List<ArtifactDefinition> nodeTypesNewCreatedArtifacts, Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo,
1667                                    String nodeName) {
1668         try {
1669             for (Map.Entry<String, NodeTypeInfo> nodeTypeEntry : nodeTypesInfo.entrySet()) {
1670                 if (nodeTypeEntry.getValue().isNested()) {
1671                     handleNestedVfc(resource, nodeTypesArtifactsToHandle, nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo,
1672                         nodeTypeEntry.getKey());
1673                     log.trace("************* finished to create node {}", nodeTypeEntry.getKey());
1674                 }
1675             }
1676             Map<String, Object> mappedToscaTemplate = null;
1677             if (org.apache.commons.lang.StringUtils.isNotEmpty(nodeName) && MapUtils.isNotEmpty(nodeTypesInfo) && nodeTypesInfo
1678                 .containsKey(nodeName)) {
1679                 mappedToscaTemplate = nodeTypesInfo.get(nodeName).getMappedToscaTemplate();
1680             }
1681             if (MapUtils.isEmpty(mappedToscaTemplate)) {
1682                 mappedToscaTemplate = (Map<String, Object>) new Yaml().load(topologyTemplateYaml);
1683             }
1684             createResourcesFromYamlNodeTypesList(yamlName, resource, mappedToscaTemplate, needLock, nodeTypesArtifactsToHandle,
1685                 nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo);
1686         } catch (ComponentException e) {
1687             ResponseFormat responseFormat =
1688                 e.getResponseFormat() != null ? e.getResponseFormat() : componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams());
1689             componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, AuditingActionEnum.IMPORT_RESOURCE);
1690             throw e;
1691         } catch (StorageException e) {
1692             ResponseFormat responseFormat = componentsUtils
1693                 .getResponseFormat(componentsUtils.convertFromStorageResponse(e.getStorageOperationStatus()));
1694             componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, AuditingActionEnum.IMPORT_RESOURCE);
1695             throw e;
1696         } catch (Exception e) {
1697             log.debug("Exception occured when handleNodeTypes, error is:{}", e.getMessage(), e);
1698             throw new ComponentException(ActionStatus.GENERAL_ERROR);
1699         }
1700     }
1701
1702     protected Resource handleNestedVfc(Service service,
1703                                        Map<String, EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>>> nodesArtifactsToHandle,
1704                                        List<ArtifactDefinition> createdArtifacts, Map<String, NodeTypeInfo> nodesInfo, CsarInfo csarInfo,
1705                                        String nodeName) {
1706         try {
1707             String yamlName = nodesInfo.get(nodeName).getTemplateFileName();
1708             Map<String, Object> nestedVfcJsonMap = nodesInfo.get(nodeName).getMappedToscaTemplate();
1709             createResourcesFromYamlNodeTypesList(yamlName, service, nestedVfcJsonMap, false, nodesArtifactsToHandle, createdArtifacts, nodesInfo,
1710                 csarInfo);
1711             log.debug("************* Finished to create node types from yaml {}", yamlName);
1712             if (nestedVfcJsonMap.containsKey(TypeUtils.ToscaTagNamesEnum.TOPOLOGY_TEMPLATE.getElementName())) {
1713                 log.debug("************* Going to handle complex VFC from yaml {}", yamlName);
1714                 return handleComplexVfc(nodesArtifactsToHandle, createdArtifacts, nodesInfo, csarInfo, nodeName, yamlName);
1715             }
1716             return new Resource();
1717         } catch (Exception e) {
1718             log.debug("Exception occured when handleNestedVFc, error is:{}", e.getMessage(), e);
1719             throw new ComponentException(ActionStatus.GENERAL_ERROR);
1720         }
1721     }
1722
1723     protected Resource handleNestedVfc(Resource resource,
1724                                        Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodesArtifactsToHandle,
1725                                        List<ArtifactDefinition> createdArtifacts, Map<String, NodeTypeInfo> nodesInfo, CsarInfo csarInfo,
1726                                        String nodeName) {
1727         String yamlName = nodesInfo.get(nodeName).getTemplateFileName();
1728         Map<String, Object> nestedVfcJsonMap = nodesInfo.get(nodeName).getMappedToscaTemplate();
1729         log.debug("************* Going to create node types from yaml {}", yamlName);
1730         createResourcesFromYamlNodeTypesList(yamlName, resource, nestedVfcJsonMap, false, nodesArtifactsToHandle, createdArtifacts, nodesInfo,
1731             csarInfo);
1732         if (nestedVfcJsonMap.containsKey(TypeUtils.ToscaTagNamesEnum.TOPOLOGY_TEMPLATE.getElementName())) {
1733             log.debug("************* Going to handle complex VFC from yaml {}", yamlName);
1734             resource = handleComplexVfc(resource, nodesArtifactsToHandle, createdArtifacts, nodesInfo, csarInfo, nodeName, yamlName);
1735         }
1736         return resource;
1737     }
1738
1739     protected Resource handleComplexVfc(Resource resource,
1740                                         Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodesArtifactsToHandle,
1741                                         List<ArtifactDefinition> createdArtifacts, Map<String, NodeTypeInfo> nodesInfo, CsarInfo csarInfo,
1742                                         String nodeName, String yamlName) {
1743         Resource oldComplexVfc = null;
1744         Resource newComplexVfc = serviceImportParseLogic.buildValidComplexVfc(resource, csarInfo, nodeName, nodesInfo);
1745         Either<Resource, StorageOperationStatus> oldComplexVfcRes = toscaOperationFacade
1746             .getFullLatestComponentByToscaResourceName(newComplexVfc.getToscaResourceName());
1747         if (oldComplexVfcRes.isRight() && oldComplexVfcRes.right().value() == StorageOperationStatus.NOT_FOUND) {
1748             oldComplexVfcRes = toscaOperationFacade.getFullLatestComponentByToscaResourceName(
1749                 serviceImportParseLogic.buildNestedToscaResourceName(ResourceTypeEnum.VF.name(), csarInfo.getVfResourceName(), nodeName).getRight());
1750         }
1751         if (oldComplexVfcRes.isRight() && oldComplexVfcRes.right().value() != StorageOperationStatus.NOT_FOUND) {
1752             throw new ComponentException(ActionStatus.GENERAL_ERROR);
1753         } else if (oldComplexVfcRes.isLeft()) {
1754             log.debug(VALIDATE_DERIVED_BEFORE_UPDATE);
1755             Either<Boolean, ResponseFormat> eitherValidation = serviceImportParseLogic
1756                 .validateNestedDerivedFromDuringUpdate(oldComplexVfcRes.left().value(), newComplexVfc,
1757                     ValidationUtils.hasBeenCertified(oldComplexVfcRes.left().value().getVersion()));
1758             if (eitherValidation.isLeft()) {
1759                 oldComplexVfc = oldComplexVfcRes.left().value();
1760             }
1761         }
1762         newComplexVfc = handleComplexVfc(nodesArtifactsToHandle, createdArtifacts, nodesInfo, csarInfo, nodeName, yamlName, oldComplexVfc,
1763             newComplexVfc);
1764         csarInfo.getCreatedNodesToscaResourceNames().put(nodeName, newComplexVfc.getToscaResourceName());
1765         LifecycleChangeInfoWithAction lifecycleChangeInfo = new LifecycleChangeInfoWithAction(CERTIFICATION_ON_IMPORT,
1766             LifecycleChangeInfoWithAction.LifecycleChanceActionEnum.CREATE_FROM_CSAR);
1767         log.debug("Going to certify cvfc {}. ", newComplexVfc.getName());
1768         final Resource result = serviceImportParseLogic
1769             .propagateStateToCertified(csarInfo.getModifier(), newComplexVfc, lifecycleChangeInfo, true, false, true);
1770         csarInfo.getCreatedNodes().put(nodeName, result);
1771         csarInfo.removeNodeFromQueue();
1772         return result;
1773     }
1774
1775     private Map<String, Resource> createResourcesFromYamlNodeTypesList(String yamlName, Resource resource, Map<String, Object> mappedToscaTemplate,
1776                                                                        boolean needLock,
1777                                                                        Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle,
1778                                                                        List<ArtifactDefinition> nodeTypesNewCreatedArtifacts,
1779                                                                        Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo) {
1780         Either<String, ImportUtils.ResultStatusEnum> toscaVersion = findFirstToscaStringElement(mappedToscaTemplate,
1781             TypeUtils.ToscaTagNamesEnum.TOSCA_VERSION);
1782         if (toscaVersion.isRight()) {
1783             throw new ComponentException(ActionStatus.INVALID_TOSCA_TEMPLATE);
1784         }
1785         Map<String, Object> mapToConvert = new HashMap<>();
1786         mapToConvert.put(TypeUtils.ToscaTagNamesEnum.TOSCA_VERSION.getElementName(), toscaVersion.left().value());
1787         Map<String, Object> nodeTypes = serviceImportParseLogic.getNodeTypesFromTemplate(mappedToscaTemplate);
1788         createNodeTypes(yamlName, resource, needLock, nodeTypesArtifactsToHandle, nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo, mapToConvert,
1789             nodeTypes);
1790         return csarInfo.getCreatedNodes();
1791     }
1792
1793     protected void createNodeTypes(String yamlName, Resource resource, boolean needLock,
1794                                    Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle,
1795                                    List<ArtifactDefinition> nodeTypesNewCreatedArtifacts, Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo,
1796                                    Map<String, Object> mapToConvert, Map<String, Object> nodeTypes) {
1797         Iterator<Map.Entry<String, Object>> nodesNameValueIter = nodeTypes.entrySet().iterator();
1798         Resource vfcCreated = null;
1799         while (nodesNameValueIter.hasNext()) {
1800             Map.Entry<String, Object> nodeType = nodesNameValueIter.next();
1801             Map<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle =
1802                 nodeTypesArtifactsToHandle == null || nodeTypesArtifactsToHandle.isEmpty() ? null : nodeTypesArtifactsToHandle.get(nodeType.getKey());
1803             if (nodeTypesInfo.containsKey(nodeType.getKey())) {
1804                 log.trace("************* Going to handle nested vfc {}", nodeType.getKey());
1805                 vfcCreated = handleNestedVfc(resource, nodeTypesArtifactsToHandle, nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo,
1806                     nodeType.getKey());
1807                 log.trace("************* Finished to handle nested vfc {}", nodeType.getKey());
1808             } else if (csarInfo.getCreatedNodesToscaResourceNames() != null && !csarInfo.getCreatedNodesToscaResourceNames()
1809                 .containsKey(nodeType.getKey())) {
1810                 log.trace("************* Going to create node {}", nodeType.getKey());
1811                 ImmutablePair<Resource, ActionStatus> resourceCreated = createNodeTypeResourceFromYaml(yamlName, nodeType, csarInfo.getModifier(),
1812                     mapToConvert, resource, needLock, nodeTypeArtifactsToHandle, nodeTypesNewCreatedArtifacts, true, csarInfo, true);
1813                 log.debug("************* Finished to create node {}", nodeType.getKey());
1814                 vfcCreated = resourceCreated.getLeft();
1815                 csarInfo.getCreatedNodesToscaResourceNames().put(nodeType.getKey(), vfcCreated.getToscaResourceName());
1816             }
1817             if (vfcCreated != null) {
1818                 csarInfo.getCreatedNodes().put(nodeType.getKey(), vfcCreated);
1819             }
1820             mapToConvert.remove(TypeUtils.ToscaTagNamesEnum.NODE_TYPES.getElementName());
1821         }
1822     }
1823
1824     protected ImmutablePair<Resource, ActionStatus> createNodeTypeResourceFromYaml(String yamlName, Map.Entry<String, Object> nodeNameValue,
1825                                                                                    User user, Map<String, Object> mapToConvert, Resource resourceVf,
1826                                                                                    boolean needLock,
1827                                                                                    Map<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle,
1828                                                                                    List<ArtifactDefinition> nodeTypesNewCreatedArtifacts,
1829                                                                                    boolean forceCertificationAllowed, CsarInfo csarInfo,
1830                                                                                    boolean isNested) {
1831         final var validatedUser = serviceBusinessLogic.validateUser(user, "CheckIn Resource", resourceVf, AuditingActionEnum.CHECKIN_RESOURCE,
1832             true);
1833         UploadResourceInfo resourceMetaData = serviceImportParseLogic.fillResourceMetadata(yamlName, resourceVf, nodeNameValue.getKey(),
1834             validatedUser);
1835         String singleVfcYaml = serviceImportParseLogic.buildNodeTypeYaml(nodeNameValue, mapToConvert, resourceMetaData.getResourceType(), csarInfo);
1836         return serviceImportParseLogic.createResourceFromNodeType(singleVfcYaml, resourceMetaData, validatedUser, true, needLock,
1837             nodeTypeArtifactsToHandle,
1838             nodeTypesNewCreatedArtifacts, forceCertificationAllowed, csarInfo, nodeNameValue.getKey(), isNested);
1839     }
1840
1841     protected Service createRIAndRelationsFromYaml(String yamlName, Service service,
1842                                                    Map<String, UploadComponentInstanceInfo> uploadComponentInstanceInfoMap,
1843                                                    String topologyTemplateYaml, List<ArtifactDefinition> nodeTypesNewCreatedArtifacts,
1844                                                    Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo,
1845                                                    Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToCreate,
1846                                                    String nodeName) {
1847         log.debug("************* Going to create all nodes {}", yamlName);
1848         handleServiceNodeTypes(yamlName, service, topologyTemplateYaml, false, nodeTypesArtifactsToCreate, nodeTypesNewCreatedArtifacts,
1849             nodeTypesInfo, csarInfo, nodeName);
1850         if (MapUtils.isNotEmpty(uploadComponentInstanceInfoMap)) {
1851             log.debug("************* Going to create all resource instances {}", yamlName);
1852             service = createServiceInstances(yamlName, service, uploadComponentInstanceInfoMap, csarInfo.getCreatedNodes());
1853             log.debug("************* Going to create all relations {}", yamlName);
1854             service = createServiceInstancesRelations(csarInfo.getModifier(), yamlName, service, uploadComponentInstanceInfoMap);
1855             log.debug("************* Going to create positions {}", yamlName);
1856             compositionBusinessLogic.setPositionsForComponentInstances(service, csarInfo.getModifier().getUserId());
1857             log.debug("************* Finished to set positions {}", yamlName);
1858         }
1859         return service;
1860     }
1861
1862     protected Service createServiceInstancesRelations(User user, String yamlName, Service service,
1863                                                       Map<String, UploadComponentInstanceInfo> uploadResInstancesMap) {
1864         log.debug("#createResourceInstancesRelations - Going to create relations ");
1865         List<ComponentInstance> componentInstancesList = service.getComponentInstances();
1866         if (MapUtils.isEmpty(uploadResInstancesMap) || CollectionUtils.isEmpty(componentInstancesList)) { // PNF can have no resource instances
1867             log.debug("#createResourceInstancesRelations - No instances found in the resource {} is empty, yaml template file name {}, ",
1868                 service.getUniqueId(), yamlName);
1869             BeEcompErrorManager.getInstance()
1870                 .logInternalDataError("createResourceInstancesRelations", "No instances found in a component or nn yaml template. ",
1871                     BeEcompErrorManager.ErrorSeverity.ERROR);
1872             throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName));
1873         }
1874         Map<String, List<ComponentInstanceProperty>> instProperties = new HashMap<>();
1875         Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilities = new HashMap<>();
1876         Map<ComponentInstance, Map<String, List<RequirementDefinition>>> instRequirements = new HashMap<>();
1877         Map<String, Map<String, ArtifactDefinition>> instDeploymentArtifacts = new HashMap<>();
1878         Map<String, Map<String, ArtifactDefinition>> instArtifacts = new HashMap<>();
1879         Map<String, List<AttributeDefinition>> instAttributes = new HashMap<>();
1880         Map<String, Resource> originCompMap = new HashMap<>();
1881         List<RequirementCapabilityRelDef> relations = new ArrayList<>();
1882         Map<String, List<ComponentInstanceInput>> instInputs = new HashMap<>();
1883         Map<String, UploadNodeFilterInfo> instNodeFilter = new HashMap<>();
1884         Map<String, Map<String, InterfaceDefinition>> instInterfaces = new HashMap<>();
1885         log.debug("enter ServiceImportBusinessLogic  createServiceInstancesRelations#createResourceInstancesRelations - Before get all datatypes. ");
1886         final ApplicationDataTypeCache applicationDataTypeCache = serviceBusinessLogic.applicationDataTypeCache;
1887         if (applicationDataTypeCache != null) {
1888             final Map<String, DataTypeDefinition> allDataTypesMap =
1889                 componentsUtils.getAllDataTypes(applicationDataTypeCache, service.getModel());
1890             final Service service1 = service;
1891             uploadResInstancesMap.values().forEach(
1892                 i -> processComponentInstance(yamlName, service1, componentInstancesList,
1893                     allDataTypesMap, instProperties,
1894                     instCapabilities, instRequirements, instDeploymentArtifacts, instArtifacts, instAttributes, originCompMap, instInputs,
1895                     instNodeFilter, instInterfaces, i)
1896             );
1897         }
1898         updatePropertyToscaFunctionData(service, instProperties, instAttributes);
1899         serviceImportParseLogic.associateComponentInstancePropertiesToComponent(yamlName, service, instProperties);
1900         serviceImportParseLogic.associateComponentInstanceInterfacesToComponent(
1901             yamlName,
1902             service,
1903             instInterfaces
1904         );
1905         serviceImportParseLogic.associateComponentInstanceInputsToComponent(yamlName, service, instInputs);
1906         serviceImportParseLogic.associateCINodeFilterToComponent(yamlName, service, instNodeFilter);
1907         serviceImportParseLogic.associateDeploymentArtifactsToInstances(user, yamlName, service, instDeploymentArtifacts);
1908         serviceImportParseLogic.associateArtifactsToInstances(yamlName, service, instArtifacts);
1909         serviceImportParseLogic.associateOrAddCalculatedCapReq(yamlName, service, instCapabilities, instRequirements);
1910         log.debug("enter createServiceInstancesRelations test,instRequirements:{},instCapabilities:{}", instRequirements, instCapabilities);
1911         serviceImportParseLogic.associateInstAttributeToComponentToInstances(yamlName, service, instAttributes);
1912         ToscaElement serviceTemplate = ModelConverter.convertToToscaElement(service);
1913         Map<String, ListCapabilityDataDefinition> capabilities = serviceTemplate.getCapabilities();
1914         Map<String, ListRequirementDataDefinition> requirements = serviceTemplate.getRequirements();
1915         serviceImportParseLogic.associateCapabilitiesToService(yamlName, service, capabilities);
1916         serviceImportParseLogic.associateRequirementsToService(yamlName, service, requirements);
1917         service = getResourceAfterCreateRelations(service);
1918         addRelationsToRI(yamlName, service, uploadResInstancesMap, componentInstancesList, relations);
1919         serviceImportParseLogic.associateResourceInstances(yamlName, service, relations);
1920         log.debug("************* in create relations, getResource start");
1921         Either<Service, StorageOperationStatus> eitherGetResource = toscaOperationFacade.getToscaElement(service.getUniqueId());
1922         log.debug("************* in create relations, getResource end");
1923         if (eitherGetResource.isRight()) {
1924             throw new ComponentException(componentsUtils
1925                 .getResponseFormatByComponent(componentsUtils.convertFromStorageResponse(eitherGetResource.right().value()), service,
1926                     service.getComponentType()));
1927         }
1928         return eitherGetResource.left().value();
1929     }
1930
1931     private void updatePropertyToscaFunctionData(final Component service,
1932                                                  final Map<String, List<ComponentInstanceProperty>> instancePropertyMap,
1933                                                  final Map<String, List<AttributeDefinition>> instanceAttributeMap) {
1934         final Component updatedService =
1935             toscaOperationFacade.getToscaElement(service.getUniqueId()).left()
1936                 .on(storageOperationStatus -> {
1937                         final ActionStatus status = componentsUtils.convertFromStorageResponse(storageOperationStatus);
1938                         final ResponseFormat responseFormat =
1939                             componentsUtils.getResponseFormatByComponent(status, service, service.getComponentType());
1940                         throw new ComponentException(responseFormat);
1941                     }
1942                 );
1943         instancePropertyMap.values().forEach(instancePropertyList ->
1944             instancePropertyList.stream()
1945                 .filter(PropertyDataDefinition::isToscaFunction)
1946                 .forEach(instanceProperty -> {
1947                     toscaFunctionService.updateFunctionWithDataFromSelfComponent(instanceProperty.getToscaFunction(),
1948                         updatedService, instancePropertyMap, instanceAttributeMap);
1949                     instanceProperty.setValue(instanceProperty.getToscaFunction().getValue());
1950                 })
1951         );
1952     }
1953
1954     protected void processComponentInstance(String yamlName, Component component, List<ComponentInstance> componentInstancesList,
1955                                             Map<String, DataTypeDefinition> allDataTypes,
1956                                             Map<String, List<ComponentInstanceProperty>> instProperties,
1957                                             Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilties,
1958                                             Map<ComponentInstance, Map<String, List<RequirementDefinition>>> instRequirements,
1959                                             Map<String, Map<String, ArtifactDefinition>> instDeploymentArtifacts,
1960                                             Map<String, Map<String, ArtifactDefinition>> instArtifacts,
1961                                             Map<String, List<AttributeDefinition>> instAttributes, Map<String, Resource> originCompMap,
1962                                             Map<String, List<ComponentInstanceInput>> instInputs,
1963                                             Map<String, UploadNodeFilterInfo> instNodeFilter,
1964                                             Map<String, Map<String, InterfaceDefinition>> instInterfaces,
1965                                             UploadComponentInstanceInfo uploadComponentInstanceInfo) {
1966         log.debug("enter ServiceImportBusinessLogic processComponentInstance");
1967         Optional<ComponentInstance> currentCompInstanceOpt = componentInstancesList.stream()
1968             .filter(i -> i.getName().equals(uploadComponentInstanceInfo.getName())).findFirst();
1969         if (currentCompInstanceOpt.isEmpty()) {
1970             log.debug(COMPONENT_INSTANCE_WITH_NAME_IN_RESOURCE, uploadComponentInstanceInfo.getName(), component.getUniqueId());
1971             BeEcompErrorManager.getInstance()
1972                 .logInternalDataError(COMPONENT_INSTANCE_WITH_NAME + uploadComponentInstanceInfo.getName() + IN_RESOURCE, component.getUniqueId(),
1973                     BeEcompErrorManager.ErrorSeverity.ERROR);
1974             ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
1975             throw new ComponentException(responseFormat);
1976         }
1977         ComponentInstance currentCompInstance = currentCompInstanceOpt.get();
1978         String resourceInstanceId = currentCompInstance.getUniqueId();
1979         Resource originResource = getOriginResource(yamlName, originCompMap, currentCompInstance);
1980         if (MapUtils.isNotEmpty(originResource.getRequirements())) {
1981             instRequirements.put(currentCompInstance, originResource.getRequirements());
1982         }
1983         if (MapUtils.isNotEmpty(originResource.getCapabilities())) {
1984             processComponentInstanceCapabilities(allDataTypes, instCapabilties, uploadComponentInstanceInfo, currentCompInstance, originResource);
1985         }
1986         if (originResource.getDeploymentArtifacts() != null && !originResource.getDeploymentArtifacts().isEmpty()) {
1987             instDeploymentArtifacts.put(resourceInstanceId, originResource.getDeploymentArtifacts());
1988         }
1989         if (originResource.getArtifacts() != null && !originResource.getArtifacts().isEmpty()) {
1990             instArtifacts.put(resourceInstanceId, originResource.getArtifacts());
1991         }
1992         if (originResource.getAttributes() != null && !originResource.getAttributes().isEmpty()) {
1993             instAttributes.put(resourceInstanceId, originResource.getAttributes());
1994             addAttributeValueToResourceInstance(instAttributes, uploadComponentInstanceInfo.getAttributes());
1995         }
1996         if (uploadComponentInstanceInfo.getUploadNodeFilterInfo() != null) {
1997             instNodeFilter.put(resourceInstanceId, uploadComponentInstanceInfo.getUploadNodeFilterInfo());
1998         }
1999         if (MapUtils.isNotEmpty(uploadComponentInstanceInfo.getInterfaces())) {
2000
2001             ResponseFormat addInterfacesToRiRes = addInterfaceValuesToRi(
2002                 uploadComponentInstanceInfo,
2003                 component,
2004                 originResource,
2005                 currentCompInstance,
2006                 instInterfaces
2007             );
2008             if (addInterfacesToRiRes.getStatus() != 200) {
2009                 throw new ComponentException(addInterfacesToRiRes);
2010             }
2011         }
2012         if (originResource.getResourceType() != ResourceTypeEnum.VF) {
2013             ResponseFormat addPropertiesValueToRiRes = addPropertyValuesToRi(uploadComponentInstanceInfo, component, originResource,
2014                 currentCompInstance, instProperties, allDataTypes);
2015             if (addPropertiesValueToRiRes.getStatus() != 200) {
2016                 throw new ComponentException(addPropertiesValueToRiRes);
2017             }
2018         } else {
2019             addInputsValuesToRi(uploadComponentInstanceInfo, component, originResource, currentCompInstance, instInputs, allDataTypes);
2020         }
2021     }
2022
2023     protected void addInputsValuesToRi(UploadComponentInstanceInfo uploadComponentInstanceInfo, Component component, Resource originResource,
2024                                        ComponentInstance currentCompInstance, Map<String, List<ComponentInstanceInput>> instInputs,
2025                                        Map<String, DataTypeDefinition> allDataTypes) {
2026         Map<String, List<UploadPropInfo>> propMap = uploadComponentInstanceInfo.getProperties();
2027         try {
2028             if (MapUtils.isNotEmpty(propMap)) {
2029                 Map<String, InputDefinition> currPropertiesMap = new HashMap<>();
2030                 List<ComponentInstanceInput> instPropList = new ArrayList<>();
2031                 if (CollectionUtils.isEmpty(originResource.getInputs())) {
2032                     log.debug("failed to find properties ");
2033                     throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND));
2034                 }
2035                 originResource.getInputs().forEach(p -> serviceImportParseLogic.addInput(currPropertiesMap, p));
2036                 for (List<UploadPropInfo> propertyList : propMap.values()) {
2037                     processProperty(component, allDataTypes, currPropertiesMap, instPropList, propertyList);
2038                 }
2039                 currPropertiesMap.values().forEach(p -> instPropList.add(new ComponentInstanceInput(p)));
2040                 instInputs.put(currentCompInstance.getUniqueId(), instPropList);
2041             }
2042         } catch (Exception e) {
2043             log.debug("failed to add Inputs Values To Ri");
2044             throw new ComponentException(ActionStatus.GENERAL_ERROR);
2045         }
2046     }
2047
2048     protected void processProperty(Component component, Map<String, DataTypeDefinition> allDataTypes,
2049                                    Map<String, InputDefinition> currPropertiesMap, List<ComponentInstanceInput> instPropList,
2050                                    List<UploadPropInfo> propertyList) {
2051         UploadPropInfo propertyInfo = propertyList.get(0);
2052         String propName = propertyInfo.getName();
2053         if (!currPropertiesMap.containsKey(propName)) {
2054             log.debug("failed to find property {} ", propName);
2055             throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND, propName));
2056         }
2057         processProperty(allDataTypes, currPropertiesMap, instPropList, propertyInfo, propName, component.getInputs());
2058     }
2059
2060     protected void processGetInput(List<GetInputValueDataDefinition> getInputValues, List<InputDefinition> inputs,
2061                                    GetInputValueDataDefinition getInputIndex) {
2062         Optional<InputDefinition> optional;
2063         if (getInputIndex != null) {
2064             optional = inputs.stream().filter(p -> p.getName().equals(getInputIndex.getInputName())).findAny();
2065             if (!optional.isPresent()) {
2066                 log.debug("Failed to find input {} ", getInputIndex.getInputName());
2067                 throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
2068             }
2069             InputDefinition inputIndex = optional.get();
2070             getInputIndex.setInputId(inputIndex.getUniqueId());
2071             getInputValues.add(getInputIndex);
2072         }
2073     }
2074
2075     private void addAttributeValueToResourceInstance(Map<String, List<AttributeDefinition>> instAttributes,
2076                                                      Map<String, UploadAttributeInfo> attributeMap) {
2077         if (attributeMap == null) {
2078             return;
2079         }
2080         attributeMap.forEach((attributeName, attributeValue) -> instAttributes.values()
2081             .forEach(value -> value.stream().filter(attr -> attr.getName().equals(attributeName)).forEach(attr -> {
2082                 if (attributeValue.getValue() instanceof Collection<?> || attributeValue.getValue() instanceof Map<?, ?>) {
2083                     Gson gson = new Gson();
2084                     String json = gson.toJson(attributeValue.getValue());
2085                     attr.setValue(json);
2086                 } else {
2087                     attr.setValue(String.valueOf(attributeValue.getValue()));
2088                 }
2089             })));
2090     }
2091
2092     protected ResponseFormat addPropertyValuesToRi(UploadComponentInstanceInfo uploadComponentInstanceInfo, Component component,
2093                                                    Resource originResource, ComponentInstance currentCompInstance,
2094                                                    Map<String, List<ComponentInstanceProperty>> instProperties,
2095                                                    Map<String, DataTypeDefinition> allDataTypes) {
2096         Map<String, List<UploadPropInfo>> propMap = uploadComponentInstanceInfo.getProperties();
2097         Map<String, PropertyDefinition> currPropertiesMap = new HashMap<>();
2098         List<PropertyDefinition> originalPropertyList = originResource.getProperties();
2099         if (MapUtils.isNotEmpty(propMap) && CollectionUtils.isEmpty(originalPropertyList)) {
2100             log.debug("failed to find properties ");
2101             return componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND);
2102         }
2103         if (CollectionUtils.isEmpty(originalPropertyList)) {
2104             return componentsUtils.getResponseFormat(ActionStatus.OK);
2105         }
2106         originalPropertyList.stream()
2107             .filter(property -> !currPropertiesMap.containsKey(property.getName()))
2108             .forEach(property -> currPropertiesMap.put(property.getName(), property));
2109         List<ComponentInstanceProperty> instPropList = new ArrayList<>();
2110         if (MapUtils.isNotEmpty(propMap)) {
2111             for (final List<UploadPropInfo> propertyList : propMap.values()) {
2112                 UploadPropInfo propertyInfo = propertyList.get(0);
2113                 String propName = propertyInfo.getName();
2114                 if (!currPropertiesMap.containsKey(propName)) {
2115                     log.debug("failed to find property {} ", propName);
2116                     return componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND, propName);
2117                 }
2118                 PropertyDefinition curPropertyDef = currPropertiesMap.get(propName);
2119                 String value = null;
2120                 final List<GetInputValueDataDefinition> getInputs = new ArrayList<>();
2121                 boolean isValidate = true;
2122                 if (propertyInfo.getValue() != null) {
2123                     getInputs.addAll(propertyInfo.getGet_input());
2124                     isValidate = getInputs.isEmpty();
2125                     if (isValidate) {
2126                         value = getPropertyJsonStringValue(propertyInfo.getValue(), curPropertyDef.getType());
2127                     } else {
2128                         value = getPropertyJsonStringValue(propertyInfo.getValue(), TypeUtils.ToscaTagNamesEnum.GET_INPUT.getElementName());
2129                     }
2130                 }
2131                 final var property = new ComponentInstanceProperty(curPropertyDef, value, null);
2132                 String validatedPropValue = serviceBusinessLogic.validatePropValueBeforeCreate(property, value, true, allDataTypes);
2133
2134                 addSubPropertyYamlToscaFunctions(validatedPropValue, value, property.getType(), propertyInfo, allDataTypes);
2135
2136                 if (CollectionUtils.isNotEmpty(propertyInfo.getSubPropertyToscaFunctions())) {
2137                     validatedPropValue = value;
2138                 }
2139
2140                 property.setValue(validatedPropValue);
2141
2142                 if (tryHandlingAsYamlToscaFunction(validatedPropValue, value, propertyInfo)) {
2143                     try {
2144                         final Object yamlValue = new Yaml().loadAs(value, Object.class);
2145                         CustomYamlFunction toscaFunction = new CustomYamlFunction();
2146                         toscaFunction.setYamlValue(yamlValue);
2147                         property.setToscaFunction(toscaFunction);
2148                     } catch (Exception exception) {
2149                         log.info("Cannot create YAML value for {}", propName);
2150                     }
2151                 } else {
2152                     property.setToscaFunction(propertyInfo.getToscaFunction());
2153                 }
2154                 property.setSubPropertyToscaFunctions(propertyInfo.getSubPropertyToscaFunctions());
2155                 if (!getInputs.isEmpty() && CollectionUtils.isEmpty(property.getSubPropertyToscaFunctions())) {
2156                     final List<GetInputValueDataDefinition> getInputValues = new ArrayList<>();
2157                     for (final GetInputValueDataDefinition getInput : getInputs) {
2158                         final List<InputDefinition> inputs = component.getInputs();
2159                         if (inputs == null || inputs.isEmpty()) {
2160                             log.debug("Failed to add property {} to instance. Inputs list is empty ", property);
2161                             serviceBusinessLogic.rollbackWithException(ActionStatus.INPUTS_NOT_FOUND,
2162                                 property.getGetInputValues().stream().map(GetInputValueDataDefinition::getInputName).collect(toList()).toString());
2163                         }
2164                         InputDefinition input = serviceImportParseLogic.findInputByName(inputs, getInput);
2165                         getInput.setInputId(input.getUniqueId());
2166                         getInputValues.add(getInput);
2167                         GetInputValueDataDefinition getInputIndex = getInput.getGetInputIndex();
2168                         if (getInputIndex != null) {
2169                             input = serviceImportParseLogic.findInputByName(inputs, getInputIndex);
2170                             getInputIndex.setInputId(input.getUniqueId());
2171                             getInputValues.add(getInputIndex);
2172                         }
2173                     }
2174                     property.setGetInputValues(getInputValues);
2175                 }
2176                 instPropList.add(property);
2177                 currPropertiesMap.remove(property.getName());
2178             }
2179         }
2180         if (!currPropertiesMap.isEmpty()) {
2181             for (PropertyDefinition value : currPropertiesMap.values()) {
2182                 instPropList.add(new ComponentInstanceProperty(value));
2183             }
2184         }
2185         instProperties.put(currentCompInstance.getUniqueId(), instPropList);
2186         return componentsUtils.getResponseFormat(ActionStatus.OK);
2187     }
2188
2189     private boolean tryHandlingAsYamlToscaFunction(String validatedPropValue, String value, UploadPropInfo propertyInfo) {
2190         return StringUtils.isEmpty(validatedPropValue) && StringUtils.isNotEmpty(value) && propertyInfo.getToscaFunction() == null
2191             && CollectionUtils.isEmpty(propertyInfo.getSubPropertyToscaFunctions());
2192     }
2193
2194     private void addSubPropertyYamlToscaFunctions(final String validatedPropValue, final String value, final String propertyType,
2195                                                   final UploadPropInfo propertyInfo, final Map<String, DataTypeDefinition> allDataTypes) {
2196         if (StringUtils.isNotEmpty(validatedPropValue) || StringUtils.isEmpty(value) || ToscaPropertyType.isValidType(propertyType) != null) {
2197             return;
2198         }
2199         try {
2200             final JsonObject jsonObject = JsonParser.parseString(value).getAsJsonObject();
2201
2202             final DataTypeDefinition dataTypeDefinition = allDataTypes.get(propertyType);
2203             final List<String> propertyNames =
2204                 dataTypeDefinition.getProperties().stream().map(PropertyDataDefinition::getName).collect(Collectors.toList());
2205
2206             boolean hasSubPropertyValues = jsonObject.entrySet().stream().allMatch(entry -> propertyNames.contains(entry.getKey()));
2207
2208             if (hasSubPropertyValues) {
2209                 for (final PropertyDefinition prop : dataTypeDefinition.getProperties()) {
2210                     if (propertyInfo.getSubPropertyToscaFunctions().stream()
2211                         .anyMatch(subPropertyToscaFunction -> subPropertyToscaFunction.getSubPropertyPath().get(0).equals(prop.getName()))) {
2212                         continue;
2213                     }
2214                     Optional<SubPropertyToscaFunction> subPropertyToscaFunction = createSubPropertyYamlToscaFunction(jsonObject, prop, allDataTypes);
2215                     if (subPropertyToscaFunction.isPresent()) {
2216                         propertyInfo.getSubPropertyToscaFunctions().add(subPropertyToscaFunction.get());
2217                     }
2218                 }
2219             }
2220         } catch (Exception exception) {
2221             log.info("Cannot create YAML value for {}", value);
2222         }
2223     }
2224
2225     private Optional<SubPropertyToscaFunction> createSubPropertyYamlToscaFunction(final JsonObject jsonObject, final PropertyDefinition prop,
2226                                                                                   final Map<String, DataTypeDefinition> allDataTypes) {
2227         JsonElement propJsonElement = jsonObject.get(prop.getName());
2228         if (propJsonElement != null) {
2229             final String subPropValue = propJsonElement.toString();
2230             final ComponentInstanceProperty subProperty = new ComponentInstanceProperty(prop, subPropValue, null);
2231             final String validateSubPropValue =
2232                 serviceBusinessLogic.validatePropValueBeforeCreate(subProperty, subPropValue, true, allDataTypes);
2233
2234             if (StringUtils.isEmpty(validateSubPropValue) && StringUtils.isNotEmpty(subPropValue)) {
2235                 try {
2236                     Object yamlValue = new Yaml().loadAs(subPropValue, Object.class);
2237                     SubPropertyToscaFunction subPropertyToscaFunction = new SubPropertyToscaFunction();
2238                     CustomYamlFunction toscaFunction = new CustomYamlFunction();
2239                     toscaFunction.setYamlValue(yamlValue);
2240                     subPropertyToscaFunction.setToscaFunction(toscaFunction);
2241                     subPropertyToscaFunction.setSubPropertyPath(Collections.singletonList(prop.getName()));
2242                     return Optional.of(subPropertyToscaFunction);
2243                 } catch (Exception exception) {
2244                     log.info("Cannot create YAML value for {}", subPropValue);
2245                 }
2246             }
2247         }
2248         return Optional.empty();
2249     }
2250
2251     protected ResponseFormat addInterfaceValuesToRi(
2252         UploadComponentInstanceInfo uploadComponentInstanceInfo,
2253         Component component,
2254         Resource originResource, ComponentInstance currentCompInstance,
2255         Map<String, Map<String, InterfaceDefinition>> instInterfaces
2256     ) {
2257         Map<String, UploadInterfaceInfo> instanceInterfacesMap = uploadComponentInstanceInfo.getInterfaces();
2258         Map<String, InterfaceDefinition> currInterfacesMap = new HashMap<>();
2259         Map<String, InterfaceDefinition> interfacesFromNodeType = originResource.getInterfaces();
2260         if ((MapUtils.isNotEmpty(instanceInterfacesMap)) && (MapUtils.isEmpty(interfacesFromNodeType))) {
2261             log.debug("failed to find interfaces ");
2262             return componentsUtils.getResponseFormat(ActionStatus.INTERFACE_NOT_FOUND_IN_COMPONENT);
2263         }
2264         if (interfacesFromNodeType == null || interfacesFromNodeType.isEmpty()) {
2265             return componentsUtils.getResponseFormat(ActionStatus.OK);
2266         }
2267         for (Map.Entry<String, InterfaceDefinition> entryInstances : interfacesFromNodeType.entrySet()) {
2268             String interfaceName = entryInstances.getKey().substring(entryInstances.getKey().lastIndexOf(".") + 1);
2269             if (!currInterfacesMap.containsKey(interfaceName)) {
2270                 currInterfacesMap.put(interfaceName, entryInstances.getValue());
2271             }
2272         }
2273
2274         Map<String, InterfaceDefinition> instInterfacesMap = new HashMap<>();
2275         if (MapUtils.isNotEmpty(instanceInterfacesMap)) {
2276             for (UploadInterfaceInfo uploadInterfaceInfo : instanceInterfacesMap.values()) {
2277                 String interfaceName = uploadInterfaceInfo.getName();
2278                 if (!currInterfacesMap.containsKey(interfaceName)) {
2279                     log.debug("failed to find interface {} ", interfaceName);
2280                     return componentsUtils.getResponseFormat(ActionStatus.INTERFACE_NOT_FOUND_IN_COMPONENT, interfaceName);
2281                 }
2282                 InterfaceDefinition currentInterfaceDef = currInterfacesMap.get(interfaceName);
2283                 Map<String, OperationDataDefinition> operationsToAdd = new HashMap<>();
2284
2285                 Map<String, OperationDataDefinition> operations = uploadInterfaceInfo.getOperations();
2286                 for (Map.Entry<String, OperationDataDefinition> operation : operations.entrySet()) {
2287                     OperationDataDefinition templateOperation = currentInterfaceDef.getOperationsMap().get(operation.getKey());
2288                     OperationDataDefinition instanceOperation = operation.getValue();
2289                     //Inputs
2290                     ListDataDefinition<OperationInputDefinition> instanceInputs = instanceOperation.getInputs();
2291                     mergeOperationInputDefinitions(templateOperation.getInputs(), instanceInputs);
2292                     templateOperation.setInputs(instanceInputs);
2293                     //Implementation
2294                     templateOperation.setImplementation(instanceOperation.getImplementation());
2295                     //Description
2296                     templateOperation.setDescription(instanceOperation.getDescription());
2297                     operationsToAdd.put(operation.getKey(), templateOperation);
2298                 }
2299                 InterfaceDefinition interfaceDef = new InterfaceDefinition();
2300                 interfaceDef.setModel(component.getModel());
2301                 interfaceDef.setType(currentInterfaceDef.getType());
2302                 interfaceDef.setUniqueId(currentInterfaceDef.getType());
2303                 interfaceDef.setDescription(uploadInterfaceInfo.getDescription());
2304                 interfaceDef.setOperations(operationsToAdd);
2305                 instInterfacesMap.put(currentInterfaceDef.getType(), interfaceDef);
2306                 currInterfacesMap.remove(interfaceName);
2307             }
2308         }
2309         if (!currInterfacesMap.isEmpty()) {
2310             for (InterfaceDefinition value : currInterfacesMap.values()) {
2311                 instInterfacesMap.put(value.getUniqueId(), value);
2312             }
2313         }
2314         instInterfaces.put(currentCompInstance.getUniqueId(), instInterfacesMap);
2315         return componentsUtils.getResponseFormat(ActionStatus.OK);
2316     }
2317
2318     private void mergeOperationInputDefinitions(ListDataDefinition<OperationInputDefinition> inputsFromNodeType,
2319                                                 ListDataDefinition<OperationInputDefinition> instanceInputs) {
2320         if (inputsFromNodeType == null || CollectionUtils.isEmpty(inputsFromNodeType.getListToscaDataDefinition()) || instanceInputs == null
2321             || CollectionUtils.isEmpty(instanceInputs.getListToscaDataDefinition())) {
2322             return;
2323         }
2324         instanceInputs.getListToscaDataDefinition().forEach(
2325             instanceInput -> inputsFromNodeType.getListToscaDataDefinition().stream().filter(
2326                 templateInput -> templateInput.getName().equals(instanceInput.getName())
2327             ).forEach(
2328                 newInstanceInput -> {
2329                     instanceInput.setSourceProperty(newInstanceInput.getSourceProperty());
2330                     instanceInput.setSource(newInstanceInput.getSource());
2331                     instanceInput.setType(newInstanceInput.getType());
2332                 }
2333             )
2334         );
2335         instanceInputs.getListToscaDataDefinition().stream()
2336             .filter(instanceInput -> inputsFromNodeType.getListToscaDataDefinition().stream().noneMatch(
2337                 inputFromNodeType -> inputFromNodeType.getName().equals(instanceInput.getName())
2338             ))
2339             .forEach(oldInput -> oldInput.setType("string"));
2340     }
2341
2342     protected void processComponentInstanceCapabilities(Map<String, DataTypeDefinition> allDataTypes,
2343                                                         Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilties,
2344                                                         UploadComponentInstanceInfo uploadComponentInstanceInfo,
2345                                                         ComponentInstance currentCompInstance, Resource originResource) {
2346         log.debug("enter processComponentInstanceCapabilities");
2347         Map<String, List<CapabilityDefinition>> originCapabilities;
2348         if (MapUtils.isNotEmpty(uploadComponentInstanceInfo.getCapabilities())) {
2349             originCapabilities = new HashMap<>();
2350             Map<String, Map<String, UploadPropInfo>> newPropertiesMap = new HashMap<>();
2351             originResource.getCapabilities().forEach((k, v) -> serviceImportParseLogic.addCapabilities(originCapabilities, k, v));
2352             uploadComponentInstanceInfo.getCapabilities().values()
2353                 .forEach(l -> serviceImportParseLogic.addCapabilitiesProperties(newPropertiesMap, l));
2354             updateCapabilityPropertiesValues(allDataTypes, originCapabilities, newPropertiesMap);
2355         } else {
2356             originCapabilities = originResource.getCapabilities();
2357         }
2358         instCapabilties.put(currentCompInstance, originCapabilities);
2359     }
2360
2361     protected void updateCapabilityPropertiesValues(Map<String, DataTypeDefinition> allDataTypes,
2362                                                     Map<String, List<CapabilityDefinition>> originCapabilities,
2363                                                     Map<String, Map<String, UploadPropInfo>> newPropertiesMap) {
2364         originCapabilities.values().stream().flatMap(Collection::stream).filter(c -> newPropertiesMap.containsKey(c.getName()))
2365             .forEach(c -> updatePropertyValues(c.getProperties(), newPropertiesMap.get(c.getName()), allDataTypes));
2366     }
2367
2368     protected void updatePropertyValues(List<ComponentInstanceProperty> properties, Map<String, UploadPropInfo> newProperties,
2369                                         Map<String, DataTypeDefinition> allDataTypes) {
2370         properties.forEach(p -> updatePropertyValue(p, newProperties.get(p.getName()), allDataTypes));
2371     }
2372
2373     protected String updatePropertyValue(ComponentInstanceProperty property, UploadPropInfo propertyInfo,
2374                                          Map<String, DataTypeDefinition> allDataTypes) {
2375         String value = null;
2376         List<GetInputValueDataDefinition> getInputs = null;
2377         boolean isValidate = true;
2378         if (null != propertyInfo && propertyInfo.getValue() != null) {
2379             getInputs = propertyInfo.getGet_input();
2380             isValidate = getInputs == null || getInputs.isEmpty();
2381             if (isValidate) {
2382                 value = getPropertyJsonStringValue(propertyInfo.getValue(), property.getType());
2383             } else {
2384                 value = getPropertyJsonStringValue(propertyInfo.getValue(), TypeUtils.ToscaTagNamesEnum.GET_INPUT.getElementName());
2385             }
2386         }
2387         property.setValue(value);
2388         return serviceBusinessLogic.validatePropValueBeforeCreate(property, value, isValidate, allDataTypes);
2389     }
2390
2391     protected Resource getOriginResource(String yamlName, Map<String, Resource> originCompMap, ComponentInstance currentCompInstance) {
2392         Resource originResource;
2393         log.debug("after enter ServiceImportBusinessLogic processComponentInstance, enter getOriginResource");
2394         if (!originCompMap.containsKey(currentCompInstance.getComponentUid())) {
2395             Either<Resource, StorageOperationStatus> getOriginResourceRes = toscaOperationFacade
2396                 .getToscaFullElement(currentCompInstance.getComponentUid());
2397             if (getOriginResourceRes.isRight()) {
2398                 ResponseFormat responseFormat = componentsUtils
2399                     .getResponseFormat(componentsUtils.convertFromStorageResponse(getOriginResourceRes.right().value()), yamlName);
2400                 throw new ComponentException(responseFormat);
2401             }
2402             originResource = getOriginResourceRes.left().value();
2403             originCompMap.put(originResource.getUniqueId(), originResource);
2404         } else {
2405             originResource = originCompMap.get(currentCompInstance.getComponentUid());
2406         }
2407         return originResource;
2408     }
2409
2410     protected Either<Resource, StorageOperationStatus> updateCalculatedCapReqWithSubstitutionMappings(Resource resource,
2411                                                                                                       Map<String, UploadComponentInstanceInfo> uploadResInstancesMap) {
2412         Either<Resource, StorageOperationStatus> updateRes = null;
2413         Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> updatedInstCapabilities = new HashMap<>();
2414         Map<ComponentInstance, Map<String, List<RequirementDefinition>>> updatedInstRequirements = new HashMap<>();
2415         StorageOperationStatus status = toscaOperationFacade.deleteAllCalculatedCapabilitiesRequirements(resource.getUniqueId());
2416         if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) {
2417             log.debug("Failed to delete all calculated capabilities and requirements of resource {} upon update. Status is {}",
2418                 resource.getUniqueId(), status);
2419             updateRes = Either.right(status);
2420         }
2421         if (updateRes == null) {
2422             fillUpdatedInstCapabilitiesRequirements(resource.getComponentInstances(), uploadResInstancesMap, updatedInstCapabilities,
2423                 updatedInstRequirements);
2424             status = toscaOperationFacade.associateOrAddCalculatedCapReq(updatedInstCapabilities, updatedInstRequirements, resource);
2425             if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) {
2426                 updateRes = Either.right(status);
2427             }
2428         }
2429         if (updateRes == null) {
2430             updateRes = Either.left(resource);
2431         }
2432         return updateRes;
2433     }
2434
2435     protected void fillUpdatedInstCapabilitiesRequirements(List<ComponentInstance> componentInstances,
2436                                                            Map<String, UploadComponentInstanceInfo> uploadResInstancesMap,
2437                                                            Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> updatedInstCapabilities,
2438                                                            Map<ComponentInstance, Map<String, List<RequirementDefinition>>> updatedInstRequirements) {
2439         componentInstances.stream().forEach(i -> {
2440             fillUpdatedInstCapabilities(updatedInstCapabilities, i, uploadResInstancesMap.get(i.getName()).getCapabilitiesNamesToUpdate());
2441             fillUpdatedInstRequirements(updatedInstRequirements, i, uploadResInstancesMap.get(i.getName()).getRequirementsNamesToUpdate());
2442         });
2443     }
2444
2445     protected void fillUpdatedInstCapabilities(Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> updatedInstCapabilties,
2446                                                ComponentInstance instance, Map<String, String> capabilitiesNamesToUpdate) {
2447         Map<String, List<CapabilityDefinition>> updatedCapabilities = new HashMap<>();
2448         Set<String> updatedCapNames = new HashSet<>();
2449         if (MapUtils.isNotEmpty(capabilitiesNamesToUpdate)) {
2450             for (Map.Entry<String, List<CapabilityDefinition>> requirements : instance.getCapabilities().entrySet()) {
2451                 updatedCapabilities.put(requirements.getKey(), requirements.getValue().stream().filter(
2452                         c -> capabilitiesNamesToUpdate.containsKey(c.getName()) && !updatedCapNames.contains(capabilitiesNamesToUpdate.get(c.getName())))
2453                     .map(c -> {
2454                         c.setParentName(c.getName());
2455                         c.setName(capabilitiesNamesToUpdate.get(c.getName()));
2456                         updatedCapNames.add(c.getName());
2457                         return c;
2458                     }).collect(toList()));
2459             }
2460         }
2461         if (MapUtils.isNotEmpty(updatedCapabilities)) {
2462             updatedInstCapabilties.put(instance, updatedCapabilities);
2463         }
2464     }
2465
2466     protected void fillUpdatedInstRequirements(Map<ComponentInstance, Map<String, List<RequirementDefinition>>> updatedInstRequirements,
2467                                                ComponentInstance instance, Map<String, String> requirementsNamesToUpdate) {
2468         Map<String, List<RequirementDefinition>> updatedRequirements = new HashMap<>();
2469         Set<String> updatedReqNames = new HashSet<>();
2470         if (MapUtils.isNotEmpty(requirementsNamesToUpdate)) {
2471             for (Map.Entry<String, List<RequirementDefinition>> requirements : instance.getRequirements().entrySet()) {
2472                 updatedRequirements.put(requirements.getKey(), requirements.getValue().stream().filter(
2473                         r -> requirementsNamesToUpdate.containsKey(r.getName()) && !updatedReqNames.contains(requirementsNamesToUpdate.get(r.getName())))
2474                     .map(r -> {
2475                         r.setParentName(r.getName());
2476                         r.setName(requirementsNamesToUpdate.get(r.getName()));
2477                         updatedReqNames.add(r.getName());
2478                         return r;
2479                     }).collect(toList()));
2480             }
2481         }
2482         if (MapUtils.isNotEmpty(updatedRequirements)) {
2483             updatedInstRequirements.put(instance, updatedRequirements);
2484         }
2485     }
2486
2487     protected void addRelationsToRI(String yamlName, Service service, Map<String, UploadComponentInstanceInfo> uploadResInstancesMap,
2488                                     List<ComponentInstance> componentInstancesList, List<RequirementCapabilityRelDef> relations) {
2489         for (Map.Entry<String, UploadComponentInstanceInfo> entry : uploadResInstancesMap.entrySet()) {
2490             UploadComponentInstanceInfo uploadComponentInstanceInfo = entry.getValue();
2491             ComponentInstance currentCompInstance = null;
2492             for (ComponentInstance compInstance : componentInstancesList) {
2493                 if (compInstance.getName().equals(uploadComponentInstanceInfo.getName())) {
2494                     currentCompInstance = compInstance;
2495                     break;
2496                 }
2497             }
2498             if (currentCompInstance == null) {
2499                 log.debug(COMPONENT_INSTANCE_WITH_NAME_IN_RESOURCE, uploadComponentInstanceInfo.getName(), service.getUniqueId());
2500                 BeEcompErrorManager.getInstance()
2501                     .logInternalDataError(COMPONENT_INSTANCE_WITH_NAME + uploadComponentInstanceInfo.getName() + IN_RESOURCE, service.getUniqueId(),
2502                         BeEcompErrorManager.ErrorSeverity.ERROR);
2503                 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
2504                 throw new ComponentException(responseFormat);
2505             }
2506             ResponseFormat addRelationToRiRes = addRelationToRI(yamlName, service, entry.getValue(), relations);
2507             if (addRelationToRiRes.getStatus() != 200) {
2508                 throw new ComponentException(addRelationToRiRes);
2509             }
2510         }
2511     }
2512
2513     protected ResponseFormat addRelationToRI(String yamlName, Service service, UploadComponentInstanceInfo nodesInfoValue,
2514                                              List<RequirementCapabilityRelDef> relations) {
2515         List<ComponentInstance> componentInstancesList = service.getComponentInstances();
2516         ComponentInstance currentCompInstance = null;
2517         for (ComponentInstance compInstance : componentInstancesList) {
2518             if (compInstance.getName().equals(nodesInfoValue.getName())) {
2519                 currentCompInstance = compInstance;
2520                 break;
2521             }
2522         }
2523         if (currentCompInstance == null) {
2524             log.debug(COMPONENT_INSTANCE_WITH_NAME_IN_RESOURCE, nodesInfoValue.getName(), service.getUniqueId());
2525             BeEcompErrorManager.getInstance()
2526                 .logInternalDataError(COMPONENT_INSTANCE_WITH_NAME + nodesInfoValue.getName() + IN_RESOURCE, service.getUniqueId(),
2527                     BeEcompErrorManager.ErrorSeverity.ERROR);
2528             return componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
2529         }
2530         String resourceInstanceId = currentCompInstance.getUniqueId();
2531         Map<String, List<UploadReqInfo>> regMap = nodesInfoValue.getRequirements();
2532         if (regMap != null) {
2533             Iterator<Map.Entry<String, List<UploadReqInfo>>> nodesRegValue = regMap.entrySet().iterator();
2534             while (nodesRegValue.hasNext()) {
2535                 Map.Entry<String, List<UploadReqInfo>> nodesRegInfoEntry = nodesRegValue.next();
2536                 List<UploadReqInfo> uploadRegInfoList = nodesRegInfoEntry.getValue();
2537                 for (UploadReqInfo uploadRegInfo : uploadRegInfoList) {
2538                     log.debug("Going to create  relation {}", uploadRegInfo.getName());
2539                     String regName = uploadRegInfo.getName();
2540                     RequirementCapabilityRelDef regCapRelDef = new RequirementCapabilityRelDef();
2541                     regCapRelDef.setFromNode(resourceInstanceId);
2542                     log.debug("try to find available requirement {} ", regName);
2543                     Either<RequirementDefinition, ResponseFormat> eitherReqStatus = serviceImportParseLogic
2544                         .findAvailableRequirement(regName, yamlName, nodesInfoValue, currentCompInstance, uploadRegInfo.getCapabilityName());
2545                     if (eitherReqStatus.isRight()) {
2546                         log.debug("failed to find available requirement {} status is {}", regName, eitherReqStatus.right().value());
2547                         return eitherReqStatus.right().value();
2548                     }
2549                     RequirementDefinition validReq = eitherReqStatus.left().value();
2550                     List<CapabilityRequirementRelationship> reqAndRelationshipPairList = regCapRelDef.getRelationships();
2551                     if (reqAndRelationshipPairList == null) {
2552                         reqAndRelationshipPairList = new ArrayList<>();
2553                     }
2554                     RelationshipInfo reqAndRelationshipPair = new RelationshipInfo();
2555                     reqAndRelationshipPair.setRequirement(regName);
2556                     reqAndRelationshipPair.setRequirementOwnerId(validReq.getOwnerId());
2557                     reqAndRelationshipPair.setRequirementUid(validReq.getUniqueId());
2558                     RelationshipImpl relationship = new RelationshipImpl();
2559                     relationship.setType(validReq.getCapability());
2560                     reqAndRelationshipPair.setRelationships(relationship);
2561                     ComponentInstance currentCapCompInstance = null;
2562                     for (ComponentInstance compInstance : componentInstancesList) {
2563                         if (compInstance.getName().equals(uploadRegInfo.getNode())) {
2564                             currentCapCompInstance = compInstance;
2565                             break;
2566                         }
2567                     }
2568                     if (currentCapCompInstance == null) {
2569                         log.debug("The component instance  with name {} not found on resource {} ", uploadRegInfo.getNode(), service.getUniqueId());
2570                         BeEcompErrorManager.getInstance()
2571                             .logInternalDataError(COMPONENT_INSTANCE_WITH_NAME + uploadRegInfo.getNode() + IN_RESOURCE, service.getUniqueId(),
2572                                 BeEcompErrorManager.ErrorSeverity.ERROR);
2573                         return componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
2574                     }
2575                     regCapRelDef.setToNode(currentCapCompInstance.getUniqueId());
2576                     log.debug("try to find aviable Capability  req name is {} ", validReq.getName());
2577                     CapabilityDefinition aviableCapForRel = serviceImportParseLogic
2578                         .findAvailableCapabilityByTypeOrName(validReq, currentCapCompInstance, uploadRegInfo);
2579                     if (aviableCapForRel == null) {
2580                         BeEcompErrorManager.getInstance().logInternalDataError(
2581                             "aviable capability was not found. req name is " + validReq.getName() + " component instance is " + currentCapCompInstance
2582                                 .getUniqueId(), service.getUniqueId(), BeEcompErrorManager.ErrorSeverity.ERROR);
2583                         return componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
2584                     }
2585                     reqAndRelationshipPair.setCapability(aviableCapForRel.getName());
2586                     reqAndRelationshipPair.setCapabilityUid(aviableCapForRel.getUniqueId());
2587                     reqAndRelationshipPair.setCapabilityOwnerId(aviableCapForRel.getOwnerId());
2588                     CapabilityRequirementRelationship capReqRel = new CapabilityRequirementRelationship();
2589                     capReqRel.setRelation(reqAndRelationshipPair);
2590                     if (StringUtils.isNotEmpty(uploadRegInfo.getRelationshipTemplate())) {
2591                         capReqRel.setOperations(getOperations(nodesInfoValue.getOperations(), uploadRegInfo.getRelationshipTemplate()));
2592                     }
2593                     reqAndRelationshipPairList.add(capReqRel);
2594                     regCapRelDef.setRelationships(reqAndRelationshipPairList);
2595                     relations.add(regCapRelDef);
2596                 }
2597             }
2598         }
2599         return componentsUtils.getResponseFormat(ActionStatus.OK, yamlName);
2600     }
2601
2602     private List<OperationUi> getOperations(final Map<String, List<OperationUi>> operations, final String relationshipTemplate) {
2603         final List<OperationUi> operationUiList = new ArrayList<>();
2604         operations.forEach((operationKey, operationValues) -> {
2605             if (operationKey.equals(relationshipTemplate)) {
2606                 operationUiList.addAll(operationValues);
2607             }
2608         });
2609         return operationUiList;
2610     }
2611
2612     protected Service getResourceAfterCreateRelations(Service service) {
2613         ComponentParametersView parametersView = serviceImportParseLogic.getComponentFilterAfterCreateRelations();
2614         Either<Service, StorageOperationStatus> eitherGetResource = toscaOperationFacade.getToscaElement(service.getUniqueId(), parametersView);
2615         if (eitherGetResource.isRight()) {
2616             serviceImportParseLogic.throwComponentExceptionByResource(eitherGetResource.right().value(), service);
2617         }
2618         return eitherGetResource.left().value();
2619     }
2620
2621     protected Service createServiceInstances(String yamlName, Service service, Map<String, UploadComponentInstanceInfo> uploadResInstancesMap,
2622                                              Map<String, Resource> nodeNamespaceMap) {
2623         Either<Resource, ResponseFormat> eitherResource = null;
2624         log.debug("createResourceInstances is {} - going to create resource instanse from CSAR", yamlName);
2625         if (MapUtils.isEmpty(uploadResInstancesMap)) { // PNF can have no resource instances
2626             ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE);
2627             throw new ComponentException(responseFormat);
2628         }
2629         Map<String, Resource> existingNodeTypeMap = new HashMap<>();
2630         if (MapUtils.isNotEmpty(nodeNamespaceMap)) {
2631             nodeNamespaceMap.forEach((k, v) -> existingNodeTypeMap.put(v.getToscaResourceName(), v));
2632         }
2633         Map<ComponentInstance, Resource> resourcesInstancesMap = new HashMap<>();
2634         uploadResInstancesMap.values()
2635             .forEach(i -> createAndAddResourceInstance(i, yamlName, service, nodeNamespaceMap, existingNodeTypeMap, resourcesInstancesMap));
2636         if (MapUtils.isNotEmpty(resourcesInstancesMap)) {
2637             try {
2638                 toscaOperationFacade.associateComponentInstancesToComponent(service, resourcesInstancesMap, false, false);
2639             } catch (StorageException exp) {
2640                 if (exp.getStorageOperationStatus() != null && exp.getStorageOperationStatus() != StorageOperationStatus.OK) {
2641                     log.debug("Failed to add component instances to container component {}", service.getName());
2642                     ResponseFormat responseFormat = componentsUtils
2643                         .getResponseFormat(componentsUtils.convertFromStorageResponse(exp.getStorageOperationStatus()));
2644                     eitherResource = Either.right(responseFormat);
2645                     throw new ComponentException(eitherResource.right().value());
2646                 }
2647             }
2648         }
2649         Either<Service, StorageOperationStatus> eitherGetResource = toscaOperationFacade
2650             .getToscaElement(service.getUniqueId(), serviceImportParseLogic.getComponentWithInstancesFilter());
2651         log.debug("*************finished to get resource {}", service.getUniqueId());
2652         if (eitherGetResource.isRight()) {
2653             ResponseFormat responseFormat = componentsUtils
2654                 .getResponseFormatByComponent(componentsUtils.convertFromStorageResponse(eitherGetResource.right().value()), service,
2655                     ComponentTypeEnum.SERVICE);
2656             throw new ComponentException(responseFormat);
2657         }
2658         if (CollectionUtils.isEmpty(eitherGetResource.left().value().getComponentInstances())) { // PNF can have no resource instances
2659             log.debug("Error when create resource instance from csar. ComponentInstances list empty");
2660             BeEcompErrorManager.getInstance().logBeDaoSystemError("Error when create resource instance from csar. ComponentInstances list empty");
2661             throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE));
2662         }
2663         return eitherGetResource.left().value();
2664     }
2665
2666     protected void createAndAddResourceInstance(UploadComponentInstanceInfo uploadComponentInstanceInfo, String yamlName, Component component,
2667                                                 Map<String, Resource> nodeNamespaceMap, Map<String, Resource> existingnodeTypeMap,
2668                                                 Map<ComponentInstance, Resource> resourcesInstancesMap) {
2669         log.debug("*************Going to create  resource instances {}", uploadComponentInstanceInfo.getName());
2670         try {
2671             if (nodeNamespaceMap.containsKey(uploadComponentInstanceInfo.getType())) {
2672                 uploadComponentInstanceInfo.setType(nodeNamespaceMap.get(uploadComponentInstanceInfo.getType()).getToscaResourceName());
2673             }
2674             Resource refResource =
2675                 validateResourceInstanceBeforeCreate(yamlName, component.getModel(), uploadComponentInstanceInfo, existingnodeTypeMap);
2676             ComponentInstance componentInstance = new ComponentInstance();
2677             componentInstance.setComponentUid(refResource.getUniqueId());
2678             Collection<String> directives = uploadComponentInstanceInfo.getDirectives();
2679             if (directives != null && !directives.isEmpty()) {
2680                 componentInstance.setDirectives(new ArrayList<>(directives));
2681             }
2682             UploadNodeFilterInfo uploadNodeFilterInfo = uploadComponentInstanceInfo.getUploadNodeFilterInfo();
2683             if (uploadNodeFilterInfo != null) {
2684                 componentInstance
2685                     .setNodeFilter(new CINodeFilterUtils().getNodeFilterDataDefinition(uploadNodeFilterInfo, componentInstance.getUniqueId()));
2686             }
2687             ComponentTypeEnum containerComponentType = component.getComponentType();
2688             NodeTypeEnum containerNodeType = containerComponentType.getNodeType();
2689             if (containerNodeType.equals(NodeTypeEnum.Resource) && MapUtils.isNotEmpty(uploadComponentInstanceInfo.getCapabilities()) && MapUtils
2690                 .isNotEmpty(refResource.getCapabilities())) {
2691                 serviceImportParseLogic.setCapabilityNamesTypes(refResource.getCapabilities(), uploadComponentInstanceInfo.getCapabilities());
2692                 Map<String, List<CapabilityDefinition>> validComponentInstanceCapabilities = serviceImportParseLogic
2693                     .getValidComponentInstanceCapabilities(refResource.getUniqueId(), refResource.getCapabilities(),
2694                         uploadComponentInstanceInfo.getCapabilities());
2695                 componentInstance.setCapabilities(validComponentInstanceCapabilities);
2696             }
2697             if (!existingnodeTypeMap.containsKey(uploadComponentInstanceInfo.getType())) {
2698                 ResponseFormat responseFormat = componentsUtils
2699                     .getResponseFormat(ActionStatus.INVALID_NODE_TEMPLATE, yamlName, uploadComponentInstanceInfo.getName(),
2700                         uploadComponentInstanceInfo.getType());
2701                 throw new ComponentException(responseFormat);
2702             }
2703             Resource origResource = existingnodeTypeMap.get(uploadComponentInstanceInfo.getType());
2704             componentInstance.setName(uploadComponentInstanceInfo.getName());
2705             componentInstance.setIcon(origResource.getIcon());
2706             resourcesInstancesMap.put(componentInstance, origResource);
2707         } catch (final ComponentException e) {
2708             throw e;
2709         } catch (final Exception e) {
2710             throw new ComponentException(ActionStatus.GENERAL_ERROR, e.getMessage());
2711         }
2712     }
2713
2714     protected Resource validateResourceInstanceBeforeCreate(String yamlName, String model, UploadComponentInstanceInfo uploadComponentInstanceInfo,
2715                                                             Map<String, Resource> nodeNamespaceMap) {
2716         Resource refResource;
2717         try {
2718             if (nodeNamespaceMap.containsKey(uploadComponentInstanceInfo.getType())) {
2719                 refResource = nodeNamespaceMap.get(uploadComponentInstanceInfo.getType());
2720             } else {
2721                 final Either<Component, StorageOperationStatus> resourceEither =
2722                     toscaOperationFacade.getLatestByToscaResourceName(uploadComponentInstanceInfo.getType(), model);
2723                 if (resourceEither.isRight()) {
2724                     ResponseFormat responseFormat = componentsUtils
2725                         .getResponseFormat(componentsUtils.convertFromStorageResponse(resourceEither.right().value()));
2726                     throw new ComponentException(responseFormat);
2727                 }
2728                 refResource = (Resource) resourceEither.left().value();
2729                 nodeNamespaceMap.put(refResource.getToscaResourceName(), refResource);
2730             }
2731             String componentState = refResource.getComponentMetadataDefinition().getMetadataDataDefinition().getState();
2732             if (componentState.equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
2733                 ResponseFormat responseFormat = componentsUtils
2734                     .getResponseFormat(ActionStatus.ILLEGAL_COMPONENT_STATE, refResource.getComponentType().getValue(), refResource.getName(),
2735                         componentState);
2736                 throw new ComponentException(responseFormat);
2737             }
2738             if (!ModelConverter.isAtomicComponent(refResource) && refResource.getResourceType() != ResourceTypeEnum.VF) {
2739                 log.debug("validateResourceInstanceBeforeCreate -  ref resource type is  ", refResource.getResourceType());
2740                 ResponseFormat responseFormat = componentsUtils
2741                     .getResponseFormat(ActionStatus.INVALID_NODE_TEMPLATE, yamlName, uploadComponentInstanceInfo.getName(),
2742                         uploadComponentInstanceInfo.getType());
2743                 throw new ComponentException(responseFormat);
2744             }
2745             return refResource;
2746         } catch (final ComponentException e) {
2747             throw e;
2748         } catch (final Exception e) {
2749             throw new ComponentException(ActionStatus.GENERAL_ERROR, e.getMessage());
2750         }
2751     }
2752
2753     protected void handleServiceNodeTypes(String yamlName, Service service, String topologyTemplateYaml, boolean needLock,
2754                                           Map<String, EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle,
2755                                           List<ArtifactDefinition> nodeTypesNewCreatedArtifacts, Map<String, NodeTypeInfo> nodeTypesInfo,
2756                                           CsarInfo csarInfo, String nodeName) {
2757         try {
2758             for (Map.Entry<String, NodeTypeInfo> nodeTypeEntry : nodeTypesInfo.entrySet()) {
2759                 boolean isResourceNotExisted = validateResourceNotExisted(nodeTypeEntry.getKey());
2760                 if (nodeTypeEntry.getValue().isNested() && isResourceNotExisted) {
2761                     handleNestedVF(service, nodeTypesArtifactsToHandle, nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo,
2762                         nodeTypeEntry.getKey());
2763                     log.trace("************* finished to create node {}", nodeTypeEntry.getKey());
2764                 }
2765             }
2766             Map<String, Object> mappedToscaTemplate = null;
2767             if (org.apache.commons.lang.StringUtils.isNotEmpty(nodeName) && MapUtils.isNotEmpty(nodeTypesInfo) && nodeTypesInfo
2768                 .containsKey(nodeName)) {
2769                 mappedToscaTemplate = nodeTypesInfo.get(nodeName).getMappedToscaTemplate();
2770             }
2771             if (MapUtils.isEmpty(mappedToscaTemplate)) {
2772                 mappedToscaTemplate = (Map<String, Object>) new Yaml().load(topologyTemplateYaml);
2773             }
2774             createResourcesFromYamlNodeTypesList(yamlName, service, mappedToscaTemplate, needLock, nodeTypesArtifactsToHandle,
2775                 nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo);
2776         } catch (ComponentException | StorageException e) {
2777             throw e;
2778         } catch (Exception e) {
2779             log.debug("Exception occured when handleServiceNodeTypes, error is:{}", e.getMessage(), e);
2780             throw new ComponentException(ActionStatus.GENERAL_ERROR);
2781         }
2782     }
2783
2784     protected boolean validateResourceNotExisted(String type) {
2785         try {
2786             Either<Resource, StorageOperationStatus> latestResource = toscaOperationFacade.getLatestResourceByToscaResourceName(type);
2787             return latestResource.isRight();
2788         } catch (Exception e) {
2789             log.debug("Exception occured when validateResourceNotExisted, error is:{}", e.getMessage(), e);
2790             throw new ComponentException(ActionStatus.GENERAL_ERROR);
2791         }
2792     }
2793
2794     protected Resource handleNestedVF(Service service,
2795                                       Map<String, EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>>> nodesArtifactsToHandle,
2796                                       List<ArtifactDefinition> createdArtifacts, Map<String, NodeTypeInfo> nodesInfo, CsarInfo csarInfo,
2797                                       String nodeName) {
2798         try {
2799             String yamlName = nodesInfo.get(nodeName).getTemplateFileName();
2800             Map<String, Object> nestedVfcJsonMap = nodesInfo.get(nodeName).getMappedToscaTemplate();
2801             createResourcesFromYamlNodeTypesList(yamlName, service, nestedVfcJsonMap, false, nodesArtifactsToHandle, createdArtifacts, nodesInfo,
2802                 csarInfo);
2803             log.debug("************* Finished to create node types from yaml {}", yamlName);
2804             if (nestedVfcJsonMap.containsKey(TypeUtils.ToscaTagNamesEnum.TOPOLOGY_TEMPLATE.getElementName())) {
2805                 log.debug("************* Going to handle complex VFC from yaml {}", yamlName);
2806                 return handleComplexVfc(nodesArtifactsToHandle, createdArtifacts, nodesInfo, csarInfo, nodeName, yamlName);
2807             }
2808             return new Resource();
2809         } catch (Exception e) {
2810             log.debug("Exception occured when handleNestedVF, error is:{}", e.getMessage(), e);
2811             throw new ComponentException(ActionStatus.GENERAL_ERROR);
2812         }
2813     }
2814
2815     protected Resource handleComplexVfc(
2816         Map<String, EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>>> nodesArtifactsToHandle,
2817         List<ArtifactDefinition> createdArtifacts, Map<String, NodeTypeInfo> nodesInfo, CsarInfo csarInfo, String nodeName, String yamlName) {
2818         try {
2819             Resource oldComplexVfc = null;
2820             Resource newComplexVfc = serviceImportParseLogic.buildValidComplexVfc(csarInfo, nodeName, nodesInfo);
2821             Either<Resource, StorageOperationStatus> oldComplexVfcRes = toscaOperationFacade
2822                 .getFullLatestComponentByToscaResourceName(newComplexVfc.getToscaResourceName());
2823             if (oldComplexVfcRes.isRight() && oldComplexVfcRes.right().value() == StorageOperationStatus.NOT_FOUND) {
2824                 oldComplexVfcRes = toscaOperationFacade.getFullLatestComponentByToscaResourceName(
2825                     serviceImportParseLogic.buildNestedToscaResourceName(ResourceTypeEnum.VF.name(), csarInfo.getVfResourceName(), nodeName)
2826                         .getRight());
2827             }
2828             if (oldComplexVfcRes.isRight() && oldComplexVfcRes.right().value() != StorageOperationStatus.NOT_FOUND) {
2829                 log.debug("Failed to fetch previous complex VFC by tosca resource name {}. Status is {}. ", newComplexVfc.getToscaResourceName(),
2830                     oldComplexVfcRes.right().value());
2831                 throw new ComponentException(ActionStatus.GENERAL_ERROR);
2832             } else if (oldComplexVfcRes.isLeft()) {
2833                 log.debug(VALIDATE_DERIVED_BEFORE_UPDATE);
2834                 Either<Boolean, ResponseFormat> eitherValidation = serviceImportParseLogic
2835                     .validateNestedDerivedFromDuringUpdate(oldComplexVfcRes.left().value(), newComplexVfc,
2836                         ValidationUtils.hasBeenCertified(oldComplexVfcRes.left().value().getVersion()));
2837                 if (eitherValidation.isLeft()) {
2838                     oldComplexVfc = oldComplexVfcRes.left().value();
2839                 }
2840             }
2841             newComplexVfc = handleComplexVfc(nodesArtifactsToHandle, createdArtifacts, nodesInfo, csarInfo, nodeName, yamlName, oldComplexVfc,
2842                 newComplexVfc);
2843             csarInfo.getCreatedNodesToscaResourceNames().put(nodeName, newComplexVfc.getToscaResourceName());
2844             LifecycleChangeInfoWithAction lifecycleChangeInfo = new LifecycleChangeInfoWithAction(CERTIFICATION_ON_IMPORT,
2845                 LifecycleChangeInfoWithAction.LifecycleChanceActionEnum.CREATE_FROM_CSAR);
2846             log.debug("Going to certify cvfc {}. ", newComplexVfc.getName());
2847             final Resource result = serviceImportParseLogic
2848                 .propagateStateToCertified(csarInfo.getModifier(), newComplexVfc, lifecycleChangeInfo, true, false, true);
2849             csarInfo.getCreatedNodes().put(nodeName, result);
2850             csarInfo.removeNodeFromQueue();
2851             return result;
2852         } catch (Exception e) {
2853             log.debug("Exception occured when handleComplexVfc, error is:{}", e.getMessage(), e);
2854             throw new ComponentException(ActionStatus.GENERAL_ERROR);
2855         }
2856     }
2857
2858     protected Resource handleComplexVfc(
2859         Map<String, EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>>> nodesArtifactsToHandle,
2860         List<ArtifactDefinition> createdArtifacts, Map<String, NodeTypeInfo> nodesInfo, CsarInfo csarInfo, String nodeName, String yamlName,
2861         Resource oldComplexVfc, Resource newComplexVfc) {
2862         Resource handleComplexVfcRes;
2863         try {
2864             Map<String, Object> mappedToscaTemplate = nodesInfo.get(nodeName).getMappedToscaTemplate();
2865             String yamlContent = new String(csarInfo.getCsar().get(yamlName));
2866             Map<String, NodeTypeInfo> newNodeTypesInfo = nodesInfo.entrySet().stream()
2867                 .collect(toMap(Map.Entry::getKey, e -> e.getValue().getUnmarkedCopy()));
2868             CsarInfo.markNestedVfc(mappedToscaTemplate, newNodeTypesInfo);
2869             if (oldComplexVfc == null) {
2870                 handleComplexVfcRes = createResourceFromYaml(newComplexVfc, yamlContent, yamlName, newNodeTypesInfo, csarInfo, nodesArtifactsToHandle,
2871                     false, true, nodeName);
2872             } else {
2873                 handleComplexVfcRes = updateResourceFromYaml(oldComplexVfc, newComplexVfc, AuditingActionEnum.UPDATE_RESOURCE_METADATA,
2874                     createdArtifacts, yamlContent, yamlName, csarInfo, newNodeTypesInfo, nodesArtifactsToHandle, nodeName, true);
2875             }
2876             return handleComplexVfcRes;
2877         } catch (Exception e) {
2878             log.debug("Exception occured when handleComplexVfc, error is:{}", e.getMessage(), e);
2879             throw new ComponentException(ActionStatus.GENERAL_ERROR);
2880         }
2881     }
2882
2883     protected Resource updateResourceFromYaml(Resource oldRresource, Resource newRresource, AuditingActionEnum actionEnum,
2884                                               List<ArtifactDefinition> createdArtifacts, String yamlFileName, String yamlFileContent,
2885                                               CsarInfo csarInfo, Map<String, NodeTypeInfo> nodeTypesInfo,
2886                                               Map<String, EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle,
2887                                               String nodeName, boolean isNested) {
2888         boolean inTransaction = true;
2889         boolean shouldLock = false;
2890         Resource preparedResource = null;
2891         ParsedToscaYamlInfo uploadComponentInstanceInfoMap = null;
2892         try {
2893             uploadComponentInstanceInfoMap = csarBusinessLogic
2894                 .getParsedToscaYamlInfo(yamlFileContent, yamlFileName, nodeTypesInfo, csarInfo, nodeName, oldRresource);
2895             Map<String, UploadComponentInstanceInfo> instances = uploadComponentInstanceInfoMap.getInstances();
2896             if (MapUtils.isEmpty(instances) && newRresource.getResourceType() != ResourceTypeEnum.PNF) {
2897                 throw new ComponentException(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlFileName);
2898             }
2899             preparedResource = updateExistingResourceByImport(newRresource, oldRresource, csarInfo.getModifier(), inTransaction, shouldLock,
2900                 isNested).left;
2901             log.trace("YAML topology file found in CSAR, file name: {}, contents: {}", yamlFileName, yamlFileContent);
2902             serviceImportParseLogic.handleResourceGenericType(preparedResource);
2903             handleNodeTypes(yamlFileName, preparedResource, yamlFileContent, shouldLock, nodeTypesArtifactsToHandle, createdArtifacts, nodeTypesInfo,
2904                 csarInfo, nodeName);
2905             preparedResource = serviceImportParseLogic.createInputsOnResource(preparedResource, uploadComponentInstanceInfoMap.getInputs());
2906             preparedResource = createResourceInstances(yamlFileName, preparedResource, instances, csarInfo.getCreatedNodes());
2907             preparedResource = createResourceInstancesRelations(csarInfo.getModifier(), yamlFileName, preparedResource, instances);
2908         } catch (ComponentException e) {
2909             ResponseFormat responseFormat =
2910                 e.getResponseFormat() == null ? componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams()) : e.getResponseFormat();
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         } catch (StorageException e) {
2916             ResponseFormat responseFormat = componentsUtils
2917                 .getResponseFormat(componentsUtils.convertFromStorageResponse(e.getStorageOperationStatus()));
2918             log.debug("#updateResourceFromYaml - failed to update resource from yaml {} .The error is {}", yamlFileName, responseFormat);
2919             componentsUtils
2920                 .auditResource(responseFormat, csarInfo.getModifier(), preparedResource == null ? oldRresource : preparedResource, actionEnum);
2921             throw e;
2922         }
2923         Either<Map<String, GroupDefinition>, ResponseFormat> validateUpdateVfGroupNamesRes = groupBusinessLogic.validateUpdateVfGroupNames(
2924             uploadComponentInstanceInfoMap.getGroups(), preparedResource.getSystemName());
2925         if (validateUpdateVfGroupNamesRes.isRight()) {
2926             throw new ComponentException(validateUpdateVfGroupNamesRes.right().value());
2927         }
2928         Map<String, GroupDefinition> groups;
2929         if (!validateUpdateVfGroupNamesRes.left().value().isEmpty()) {
2930             groups = validateUpdateVfGroupNamesRes.left().value();
2931         } else {
2932             groups = uploadComponentInstanceInfoMap.getGroups();
2933         }
2934         serviceImportParseLogic.handleGroupsProperties(preparedResource, groups);
2935         preparedResource = serviceImportParseLogic.updateGroupsOnResource(preparedResource, groups);
2936         NodeTypeInfoToUpdateArtifacts nodeTypeInfoToUpdateArtifacts = new NodeTypeInfoToUpdateArtifacts(nodeName, nodeTypesArtifactsToHandle);
2937         Either<Resource, ResponseFormat> updateArtifactsEither = createOrUpdateArtifacts(ArtifactsBusinessLogic.ArtifactOperationEnum.UPDATE,
2938             createdArtifacts, yamlFileName, csarInfo, preparedResource, nodeTypeInfoToUpdateArtifacts, inTransaction, shouldLock);
2939         if (updateArtifactsEither.isRight()) {
2940             log.debug("failed to update artifacts {}", updateArtifactsEither.right().value());
2941             throw new ComponentException(updateArtifactsEither.right().value());
2942         }
2943         preparedResource = serviceImportParseLogic.getResourceWithGroups(updateArtifactsEither.left().value().getUniqueId());
2944         ActionStatus mergingPropsAndInputsStatus = resourceDataMergeBusinessLogic.mergeResourceEntities(oldRresource, preparedResource);
2945         if (mergingPropsAndInputsStatus != ActionStatus.OK) {
2946             ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(mergingPropsAndInputsStatus, preparedResource);
2947             throw new ComponentException(responseFormat);
2948         }
2949         compositionBusinessLogic.setPositionsForComponentInstances(preparedResource, csarInfo.getModifier().getUserId());
2950         return preparedResource;
2951     }
2952
2953     protected Resource createResourceFromYaml(Resource resource, String topologyTemplateYaml, String yamlName,
2954                                               Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo,
2955                                               Map<String, EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToCreate,
2956                                               boolean shouldLock, boolean inTransaction, String nodeName) {
2957         List<ArtifactDefinition> createdArtifacts = new ArrayList<>();
2958         Resource createdResource;
2959         try {
2960             ParsedToscaYamlInfo parsedToscaYamlInfo = csarBusinessLogic
2961                 .getParsedToscaYamlInfo(topologyTemplateYaml, yamlName, nodeTypesInfo, csarInfo, nodeName, resource);
2962             if (MapUtils.isEmpty(parsedToscaYamlInfo.getInstances()) && resource.getResourceType() != ResourceTypeEnum.PNF) {
2963                 throw new ComponentException(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
2964             }
2965             log.debug("#createResourceFromYaml - Going to create resource {} and RIs ", resource.getName());
2966             createdResource = createResourceAndRIsFromYaml(yamlName, resource, parsedToscaYamlInfo, AuditingActionEnum.IMPORT_RESOURCE, false,
2967                 createdArtifacts, topologyTemplateYaml, nodeTypesInfo, csarInfo, nodeTypesArtifactsToCreate, shouldLock, inTransaction, nodeName);
2968             log.debug("#createResourceFromYaml - The resource {} has been created ", resource.getName());
2969         } catch (ComponentException e) {
2970             ResponseFormat responseFormat =
2971                 e.getResponseFormat() == null ? componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams()) : e.getResponseFormat();
2972             componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, AuditingActionEnum.IMPORT_RESOURCE);
2973             throw e;
2974         } catch (StorageException e) {
2975             ResponseFormat responseFormat = componentsUtils
2976                 .getResponseFormat(componentsUtils.convertFromStorageResponse(e.getStorageOperationStatus()));
2977             componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, AuditingActionEnum.IMPORT_RESOURCE);
2978             throw e;
2979         }
2980         return createdResource;
2981     }
2982
2983     protected Resource createResourceAndRIsFromYaml(String yamlName, Resource resource, ParsedToscaYamlInfo parsedToscaYamlInfo,
2984                                                     AuditingActionEnum actionEnum, boolean isNormative, List<ArtifactDefinition> createdArtifacts,
2985                                                     String topologyTemplateYaml, Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo,
2986                                                     Map<String, EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToCreate,
2987                                                     boolean shouldLock, boolean inTransaction, String nodeName) {
2988         List<ArtifactDefinition> nodeTypesNewCreatedArtifacts = new ArrayList<>();
2989         if (shouldLock) {
2990             Either<Boolean, ResponseFormat> lockResult = serviceBusinessLogic
2991                 .lockComponentByName(resource.getSystemName(), resource, CREATE_RESOURCE);
2992             if (lockResult.isRight()) {
2993                 serviceImportParseLogic.rollback(inTransaction, resource, createdArtifacts, nodeTypesNewCreatedArtifacts);
2994                 throw new ComponentException(lockResult.right().value());
2995             }
2996             log.debug("name is locked {} status = {}", resource.getSystemName(), lockResult);
2997         }
2998         try {
2999             log.trace("************* createResourceFromYaml before full create resource {}", yamlName);
3000             Resource genericResource = serviceBusinessLogic.fetchAndSetDerivedFromGenericType(resource);
3001             resource = createResourceTransaction(resource, csarInfo.getModifier(), isNormative);
3002             log.trace("************* Going to add inputs from yaml {}", yamlName);
3003             Map<String, Object> yamlMap = ImportUtils.loadYamlAsStrictMap(csarInfo.getMainTemplateContent());
3004             Map<String, Object> metadata = (Map<String, Object>) yamlMap.get("metadata");
3005             String type = (String) metadata.get("type");
3006             if (resource.shouldGenerateInputs() && !"Service".equalsIgnoreCase(type)) {
3007                 serviceBusinessLogic.generateAndAddInputsFromGenericTypeProperties(resource, genericResource);
3008             }
3009             Map<String, InputDefinition> inputs = parsedToscaYamlInfo.getInputs();
3010             resource = serviceImportParseLogic.createInputsOnResource(resource, inputs);
3011             Map<String, UploadComponentInstanceInfo> uploadComponentInstanceInfoMap = parsedToscaYamlInfo.getInstances();
3012             resource = createRIAndRelationsFromYaml(yamlName, resource, uploadComponentInstanceInfoMap, topologyTemplateYaml,
3013                 nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo, nodeTypesArtifactsToCreate, nodeName);
3014             log.trace("************* Finished to create nodes, RI and Relation  from yaml {}", yamlName);
3015             // validate update vf module group names
3016             Either<Map<String, GroupDefinition>, ResponseFormat> validateUpdateVfGroupNamesRes = groupBusinessLogic.validateUpdateVfGroupNames(
3017                 parsedToscaYamlInfo.getGroups(), resource.getSystemName());
3018             if (validateUpdateVfGroupNamesRes.isRight()) {
3019                 serviceImportParseLogic.rollback(inTransaction, resource, createdArtifacts, nodeTypesNewCreatedArtifacts);
3020                 throw new ComponentException(validateUpdateVfGroupNamesRes.right().value());
3021             }
3022             Map<String, GroupDefinition> groups;
3023             log.trace("************* Going to add groups from yaml {}", yamlName);
3024             if (!validateUpdateVfGroupNamesRes.left().value().isEmpty()) {
3025                 groups = validateUpdateVfGroupNamesRes.left().value();
3026             } else {
3027                 groups = parsedToscaYamlInfo.getGroups();
3028             }
3029             Either<Resource, ResponseFormat> createGroupsOnResource = createGroupsOnResource(resource, groups);
3030             if (createGroupsOnResource.isRight()) {
3031                 serviceImportParseLogic.rollback(inTransaction, resource, createdArtifacts, nodeTypesNewCreatedArtifacts);
3032                 throw new ComponentException(createGroupsOnResource.right().value());
3033             }
3034             resource = createGroupsOnResource.left().value();
3035             log.trace("************* Going to add artifacts from yaml {}", yamlName);
3036             NodeTypeInfoToUpdateArtifacts nodeTypeInfoToUpdateArtifacts = new NodeTypeInfoToUpdateArtifacts(nodeName, nodeTypesArtifactsToCreate);
3037             Either<Resource, ResponseFormat> createArtifactsEither = createOrUpdateArtifacts(ArtifactsBusinessLogic.ArtifactOperationEnum.CREATE,
3038                 createdArtifacts, yamlName, csarInfo, resource, nodeTypeInfoToUpdateArtifacts, inTransaction, shouldLock);
3039             if (createArtifactsEither.isRight()) {
3040                 serviceImportParseLogic.rollback(inTransaction, resource, createdArtifacts, nodeTypesNewCreatedArtifacts);
3041                 throw new ComponentException(createArtifactsEither.right().value());
3042             }
3043             resource = serviceImportParseLogic.getResourceWithGroups(createArtifactsEither.left().value().getUniqueId());
3044             ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.CREATED);
3045             componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, actionEnum);
3046             ASDCKpiApi.countCreatedResourcesKPI();
3047             return resource;
3048         } catch (ComponentException | StorageException e) {
3049             serviceImportParseLogic.rollback(inTransaction, resource, createdArtifacts, nodeTypesNewCreatedArtifacts);
3050             throw e;
3051         } finally {
3052             if (!inTransaction) {
3053                 janusGraphDao.commit();
3054             }
3055             if (shouldLock) {
3056                 graphLockOperation.unlockComponentByName(resource.getSystemName(), resource.getUniqueId(), NodeTypeEnum.Resource);
3057             }
3058         }
3059     }
3060
3061     protected Either<Resource, ResponseFormat> createGroupsOnResource(Resource resource, Map<String, GroupDefinition> groups) {
3062         if (groups != null && !groups.isEmpty()) {
3063             List<GroupDefinition> groupsAsList = updateGroupsMembersUsingResource(groups, resource);
3064             serviceImportParseLogic.handleGroupsProperties(resource, groups);
3065             serviceImportParseLogic.fillGroupsFinalFields(groupsAsList);
3066             Either<List<GroupDefinition>, ResponseFormat> createGroups = groupBusinessLogic.createGroups(resource, groupsAsList, true);
3067             if (createGroups.isRight()) {
3068                 return Either.right(createGroups.right().value());
3069             }
3070         } else {
3071             return Either.left(resource);
3072         }
3073         Either<Resource, StorageOperationStatus> updatedResource = toscaOperationFacade.getToscaElement(resource.getUniqueId());
3074         if (updatedResource.isRight()) {
3075             ResponseFormat responseFormat = componentsUtils
3076                 .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(updatedResource.right().value()), resource);
3077             return Either.right(responseFormat);
3078         }
3079         return Either.left(updatedResource.left().value());
3080     }
3081
3082     protected List<GroupDefinition> updateGroupsMembersUsingResource(Map<String, GroupDefinition> groups, Resource component) {
3083         List<GroupDefinition> result = new ArrayList<>();
3084         List<ComponentInstance> componentInstances = component.getComponentInstances();
3085         if (groups != null) {
3086             for (Map.Entry<String, GroupDefinition> entry : groups.entrySet()) {
3087                 String groupName = entry.getKey();
3088                 GroupDefinition groupDefinition = entry.getValue();
3089                 GroupDefinition updatedGroupDefinition = new GroupDefinition(groupDefinition);
3090                 updatedGroupDefinition.setMembers(null);
3091                 Map<String, String> members = groupDefinition.getMembers();
3092                 if (members != null) {
3093                     updateGroupMembers(groups, updatedGroupDefinition, component, componentInstances, groupName, members);
3094                 }
3095                 result.add(updatedGroupDefinition);
3096             }
3097         }
3098         return result;
3099     }
3100
3101     protected void updateGroupMembers(Map<String, GroupDefinition> groups, GroupDefinition updatedGroupDefinition, Resource component,
3102                                       List<ComponentInstance> componentInstances, String groupName, Map<String, String> members) {
3103         Set<String> compInstancesNames = members.keySet();
3104         if (CollectionUtils.isEmpty(componentInstances)) {
3105             String membersAstString = compInstancesNames.stream().collect(joining(","));
3106             log.debug("The members: {}, in group: {}, cannot be found in component {}. There are no component instances.", membersAstString,
3107                 groupName, component.getNormalizedName());
3108             throw new ComponentException(componentsUtils
3109                 .getResponseFormat(ActionStatus.GROUP_INVALID_COMPONENT_INSTANCE, membersAstString, groupName, component.getNormalizedName(),
3110                     serviceImportParseLogic.getComponentTypeForResponse(component)));
3111         }
3112         Map<String, String> memberNames = componentInstances.stream().collect(toMap(ComponentInstance::getName, ComponentInstance::getUniqueId));
3113         memberNames.putAll(groups.keySet().stream().collect(toMap(g -> g, g -> "")));
3114         Map<String, String> relevantInstances = memberNames.entrySet().stream().filter(n -> compInstancesNames.contains(n.getKey()))
3115             .collect(toMap(Map.Entry::getKey, Map.Entry::getValue));
3116         if (relevantInstances == null || relevantInstances.size() != compInstancesNames.size()) {
3117             List<String> foundMembers = new ArrayList<>();
3118             if (relevantInstances != null) {
3119                 foundMembers = relevantInstances.keySet().stream().collect(toList());
3120             }
3121             compInstancesNames.removeAll(foundMembers);
3122             String membersAstString = compInstancesNames.stream().collect(joining(","));
3123             throw new ComponentException(componentsUtils
3124                 .getResponseFormat(ActionStatus.GROUP_INVALID_COMPONENT_INSTANCE, membersAstString, groupName, component.getNormalizedName(),
3125                     serviceImportParseLogic.getComponentTypeForResponse(component)));
3126         }
3127         updatedGroupDefinition.setMembers(relevantInstances);
3128     }
3129
3130     protected Resource createResourceTransaction(Resource resource, User user, boolean isNormative) {
3131         Either<Boolean, StorageOperationStatus> eitherValidation = toscaOperationFacade
3132             .validateComponentNameExists(resource.getName(), resource.getResourceType(), resource.getComponentType());
3133         if (eitherValidation.isRight()) {
3134             ResponseFormat errorResponse = componentsUtils
3135                 .getResponseFormat(componentsUtils.convertFromStorageResponse(eitherValidation.right().value()));
3136             throw new ComponentException(errorResponse);
3137         }
3138         if (Boolean.TRUE.equals(eitherValidation.left().value())) {
3139             log.debug("resource with name: {}, already exists", resource.getName());
3140             ResponseFormat errorResponse = componentsUtils
3141                 .getResponseFormat(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, ComponentTypeEnum.RESOURCE.getValue(), resource.getName());
3142             throw new ComponentException(errorResponse);
3143         }
3144         log.debug("send resource {} to dao for create", resource.getName());
3145         serviceImportParseLogic.createArtifactsPlaceHolderData(resource, user);
3146         if (!isNormative) {
3147             log.debug("enrich resource with creator, version and state");
3148             resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
3149             resource.setVersion(INITIAL_VERSION);
3150             resource.setHighestVersion(true);
3151             if (resource.getResourceType() != null && resource.getResourceType() != ResourceTypeEnum.VF) {
3152                 resource.setAbstract(false);
3153             }
3154         }
3155         return toscaOperationFacade.createToscaComponent(resource).left()
3156             .on(r -> serviceImportParseLogic.throwComponentExceptionByResource(r, resource));
3157     }
3158
3159     protected ImmutablePair<Resource, ActionStatus> updateExistingResourceByImport(Resource newResource, Resource oldResource, User user,
3160                                                                                    boolean inTransaction, boolean needLock, boolean isNested) {
3161         String lockedResourceId = oldResource.getUniqueId();
3162         log.debug("found resource: name={}, id={}, version={}, state={}", oldResource.getName(), lockedResourceId, oldResource.getVersion(),
3163             oldResource.getLifecycleState());
3164         ImmutablePair<Resource, ActionStatus> resourcePair = null;
3165         try {
3166             serviceBusinessLogic.lockComponent(lockedResourceId, oldResource, needLock, "Update Resource by Import");
3167             oldResource = serviceImportParseLogic.prepareResourceForUpdate(oldResource, newResource, user, inTransaction, false);
3168             serviceImportParseLogic.mergeOldResourceMetadataWithNew(oldResource, newResource);
3169             serviceImportParseLogic.validateResourceFieldsBeforeUpdate(oldResource, newResource, inTransaction, isNested);
3170             serviceImportParseLogic.validateCapabilityTypesCreate(user, serviceImportParseLogic.getCapabilityTypeOperation(), newResource,
3171                 AuditingActionEnum.IMPORT_RESOURCE, inTransaction);
3172             createNewResourceToOldResource(newResource, oldResource, user);
3173             Either<Resource, StorageOperationStatus> overrideResource = toscaOperationFacade.overrideComponent(newResource, oldResource);
3174             if (overrideResource.isRight()) {
3175                 ResponseFormat responseFormat = new ResponseFormat();
3176                 serviceBusinessLogic.throwComponentException(responseFormat);
3177             }
3178             log.debug("Resource updated successfully!!!");
3179             resourcePair = new ImmutablePair<>(overrideResource.left().value(), ActionStatus.OK);
3180             return resourcePair;
3181         } finally {
3182             if (resourcePair == null) {
3183                 BeEcompErrorManager.getInstance().logBeSystemError("Change LifecycleState - Certify");
3184                 janusGraphDao.rollback();
3185             } else if (!inTransaction) {
3186                 janusGraphDao.commit();
3187             }
3188             if (needLock) {
3189                 log.debug("unlock resource {}", lockedResourceId);
3190                 graphLockOperation.unlockComponent(lockedResourceId, NodeTypeEnum.Resource);
3191             }
3192         }
3193     }
3194
3195     protected void createNewResourceToOldResource(Resource newResource, Resource oldResource, User user) {
3196         newResource.setContactId(newResource.getContactId().toLowerCase());
3197         newResource.setCreatorUserId(user.getUserId());
3198         newResource.setCreatorFullName(user.getFullName());
3199         newResource.setLastUpdaterUserId(user.getUserId());
3200         newResource.setLastUpdaterFullName(user.getFullName());
3201         newResource.setUniqueId(oldResource.getUniqueId());
3202         newResource.setVersion(oldResource.getVersion());
3203         newResource.setInvariantUUID(oldResource.getInvariantUUID());
3204         newResource.setLifecycleState(oldResource.getLifecycleState());
3205         newResource.setUUID(oldResource.getUUID());
3206         newResource.setNormalizedName(oldResource.getNormalizedName());
3207         newResource.setSystemName(oldResource.getSystemName());
3208         if (oldResource.getCsarUUID() != null) {
3209             newResource.setCsarUUID(oldResource.getCsarUUID());
3210         }
3211         if (oldResource.getCsarVersionId() != null) {
3212             newResource.setCsarVersionId(oldResource.getCsarVersionId());
3213         }
3214         if (oldResource.getImportedToscaChecksum() != null) {
3215             newResource.setImportedToscaChecksum(oldResource.getImportedToscaChecksum());
3216         }
3217         if (newResource.getDerivedFromGenericType() == null || newResource.getDerivedFromGenericType().isEmpty()) {
3218             newResource.setDerivedFromGenericType(oldResource.getDerivedFromGenericType());
3219         }
3220         if (newResource.getDerivedFromGenericVersion() == null || newResource.getDerivedFromGenericVersion().isEmpty()) {
3221             newResource.setDerivedFromGenericVersion(oldResource.getDerivedFromGenericVersion());
3222         }
3223         if (newResource.getToscaArtifacts() == null || newResource.getToscaArtifacts().isEmpty()) {
3224             serviceBusinessLogic.setToscaArtifactsPlaceHolders(newResource, user);
3225         }
3226         if (newResource.getInterfaces() == null || newResource.getInterfaces().isEmpty()) {
3227             newResource.setInterfaces(oldResource.getInterfaces());
3228         }
3229         if (CollectionUtils.isEmpty(newResource.getProperties())) {
3230             newResource.setProperties(oldResource.getProperties());
3231         }
3232         if (newResource.getModel() == null) {
3233             newResource.setModel(oldResource.getModel());
3234         }
3235     }
3236
3237     protected Map<String, Resource> createResourcesFromYamlNodeTypesList(String yamlName, Service service, Map<String, Object> mappedToscaTemplate,
3238                                                                          boolean needLock,
3239                                                                          Map<String, EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle,
3240                                                                          List<ArtifactDefinition> nodeTypesNewCreatedArtifacts,
3241                                                                          Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo) {
3242         try {
3243             Either<String, ImportUtils.ResultStatusEnum> toscaVersion = findFirstToscaStringElement(mappedToscaTemplate,
3244                 TypeUtils.ToscaTagNamesEnum.TOSCA_VERSION);
3245             if (toscaVersion.isRight()) {
3246                 throw new ComponentException(ActionStatus.INVALID_TOSCA_TEMPLATE);
3247             }
3248             Map<String, Object> mapToConvert = new HashMap<>();
3249             mapToConvert.put(TypeUtils.ToscaTagNamesEnum.TOSCA_VERSION.getElementName(), toscaVersion.left().value());
3250             Map<String, Object> nodeTypes = serviceImportParseLogic.getNodeTypesFromTemplate(mappedToscaTemplate);
3251             createNodeTypes(yamlName, service, needLock, nodeTypesArtifactsToHandle, nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo,
3252                 mapToConvert, nodeTypes);
3253             return csarInfo.getCreatedNodes();
3254         } catch (Exception e) {
3255             log.debug("Exception occured when createResourcesFromYamlNodeTypesList,error is:{}", e.getMessage(), e);
3256             throw new ComponentException(ActionStatus.GENERAL_ERROR);
3257         }
3258     }
3259
3260     protected void createNodeTypes(String yamlName, Service service, boolean needLock,
3261                                    Map<String, EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle,
3262                                    List<ArtifactDefinition> nodeTypesNewCreatedArtifacts, Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo,
3263                                    Map<String, Object> mapToConvert, Map<String, Object> nodeTypes) {
3264         Iterator<Map.Entry<String, Object>> nodesNameValueIter = nodeTypes.entrySet().iterator();
3265         Resource vfcCreated = null;
3266         while (nodesNameValueIter.hasNext()) {
3267             Map.Entry<String, Object> nodeType = nodesNameValueIter.next();
3268             String nodeTypeKey = nodeType.getKey();
3269             Map<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle =
3270                 nodeTypesArtifactsToHandle == null || nodeTypesArtifactsToHandle.isEmpty() ? null : nodeTypesArtifactsToHandle.get(nodeTypeKey);
3271             if (nodeTypesInfo.containsKey(nodeTypeKey)) {
3272                 vfcCreated = handleNestedVfc(service, nodeTypesArtifactsToHandle, nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo,
3273                     nodeTypeKey);
3274                 log.trace("************* Finished to handle nested vfc {}", nodeTypeKey);
3275             } else if (csarInfo.getCreatedNodesToscaResourceNames() != null && !csarInfo.getCreatedNodesToscaResourceNames()
3276                 .containsKey(nodeTypeKey)) {
3277                 ImmutablePair<Resource, ActionStatus> resourceCreated = serviceImportParseLogic
3278                     .createNodeTypeResourceFromYaml(yamlName, nodeType, csarInfo.getModifier(), mapToConvert, service, needLock,
3279                         nodeTypeArtifactsToHandle, nodeTypesNewCreatedArtifacts, true, csarInfo, true);
3280                 log.debug("************* Finished to create node {}", nodeTypeKey);
3281                 vfcCreated = resourceCreated.getLeft();
3282                 csarInfo.getCreatedNodesToscaResourceNames().put(nodeTypeKey, vfcCreated.getName());
3283             }
3284             if (vfcCreated != null) {
3285                 csarInfo.getCreatedNodes().put(nodeTypeKey, vfcCreated);
3286             }
3287             mapToConvert.remove(TypeUtils.ToscaTagNamesEnum.NODE_TYPES.getElementName());
3288         }
3289     }
3290 }