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