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