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